Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lookup vs. groupby [duplicate]

Tags:

c#

.net

linq

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.

like image 748
Marco B. Avatar asked Dec 06 '12 08:12

Marco B.


2 Answers

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.

like image 52
Jon Skeet Avatar answered Nov 17 '22 17:11

Jon Skeet


  1. ToLookup is buffered. groupBy iterates the groups.
  2. groupBy uses deffered execution while ToLookup uses immediate.
like image 31
J. Davidson Avatar answered Nov 17 '22 18:11

J. Davidson