I'm wondering what's the difference between the groupBy and the ToLookup Extension Method.
Let us have a List of objects like this:
public class Person
{
public uint Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
}
List<Person> People { get; set; }
Now i can use the Extension Methods above:
var groupedPeople = People.GroupBy((x) => x.Id);
var lookupPeople = People.ToLookup((x) => x.Id);
What's the difference between those statements?
Thanks in advance.
Marco B.
ToLookup
uses immediate execution, and returns an ILookup
which allows you to look the groups up by key.
GroupBy
uses deferred execution, and just returns you groups in the order in which each group was first encountered (so the first group will contain the first element of the source data, for example), with no idea of being able to look the groups up later by key. Each time you iterate over the results, it will have to group again.
Basically, which you should use depends on what you're going to do with the results. If you're just going to iterate over them a single time (e.g. for further transformation), GroupBy
is usually fine. If you want to keep them as a collection for multiple operations, the immediate nature of ToLookup
is useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With