2

I am trying to retrieve a list of names from a large IEnumerable with 142000 objects. For some reason.. the operation is timing out and leaving an incomplete list of names. Is there a better and faster way to do what I am doing in the code below:

IEnumerable<MyClass> table = GetAll(); // Get All returns an IEnumerable<MyClass>

IEnumerable<string> allNames = new List<string>();
allNames = table.Where(r => listOfIds.Contains(r.id)).Select(r => r.name);

Any help appreciated,

Ted

Flethuseo
  • 5,969
  • 11
  • 47
  • 71

1 Answers1

4

This should be more efficient:

List<String> allNames = (from id in listOfIds
                         join t in table on id equals t.id
                         select t.name).ToList();

Why is LINQ JOIN so much faster than linking with WHERE?

By the way, Join is 1262 faster here than your Where above with 142000 objects and 50000 ID's.

79 millis vs. 99705 millis

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • I just had a look at your linked question and found it very interesting. However, as i read more into it, I realised that what you're referring to (LINQ to DataSet and LINQ to Object) is very different from what I assumed, which was LINQ to SQL and LINQ to Entities. So just a warning that the title is misleading. If using Linq to Entities or SQL, the query is actually built on the sql side and thus negates much of the performance benefits of a join over a where. – Joe May 30 '12 at 23:15
  • @Joe: Why is the title misleading? There's no relation to LINQ-To-SQL/Entities. Apart from that OP is using LINQ-To-Objects ;) – Tim Schmelter May 30 '12 at 23:20
  • yes, i know i'm probably being a bit pedantic here, the OP **is** using linq to objects, but when i read that *linq join is faster than where* and i am a prolific user of `Table.Where(condition)` i thought to myself, wow here's a awesome speed upgrade i just found out about. Then after i read about it, i realised that I should have probably read it as *Linq to object/dataset join is so much faster than where*. the point is that it's not true for all kinds of linq. aside: i didn't know the difference between linq to object vs dataset vs entities before this. – Joe May 30 '12 at 23:26