Looping Over a Large Collection of Data

Programming C# performance LINQ

There is not a single application without looping and iteration over a collection of data.  There are times when you would have to find a value, find a node, find a record, or perform any other traversing over the collection.

In such cases, you really need to make sure you are writing clean code, as this is the area where both performance and readability matter a lot and they are correlated. That is exactly where LINQ experience should jump in and allow you to write programs that use the best of .NET framework to provide the best coding experience and the best experience to your users and customers.

Consider this three different implementation approaches:

public Person FindPersonOption1(int id)
{
var people = DbContext.GetPeople(); // returns List<Person>

foreach (var person in people)
{
if (person.ID == id)
{
return person;
}
}

// No person found.
return null;
}

public Person FindPersonOption2(int id)
{
var people = DbContext.GetPeople(); // returns List<Person>

return (from person in people
where person.ID == id
select person).ToList().FirstOrDefault();
}

public Person FindPersonOption3(int id)
{
return DbContext
.GetPeople()
.FirstOrDefault(x => x.ID == id);
}

Developer or not, everyone is able to understand what option #1 is doing.  It's just... unnecessary hacking into the keyboard. And if's in a loop  wont make your application faster, that's for shure.

Option #2 utilizes the SQL-like way of using LINQ. This reads even better and leaves everything iteration oriented to .NET framework itself. The .NET framework would provide best performance to the applications.  But still too much hacking into the keyboard. 

Therefore option #3 with the Lamda LINQ style comes to rescue - just a single line of code without any iteration.

Notice that the code in option #1 returned null in the case when there was no match found. The other code options also do the same thing.