I haven’t done much LINQ before, so I often find some aspects confusing. Recently someone created a query that looks like the following using the GroupBy operator. Here’s what they did:
List<int> ranges = new List<int>() {100, 1000, 1000000};
List<int> sizes = new List<int>(new int[]{99,98,10,5,5454, 12432, 11, 12432, 992, 56, 222});
var xx = sizes.GroupBy (size => ranges.First(range => range >= size));
xx.Dump();
Basically I am very quite confused as to how the key expression works, i.e. ranges.First(range => range >= size
Can anyone shed some light? Can it be decomposed further to make this easier to understand? I thought that First would produce one result.
Thanks in advance.
size => ranges.First(range => range >= size)this Func builds key, on which sizes will be grouped. It takes current size and finds first range, which is greater or equal current size.How it works:
For size
99first range which>= 99is100. So, calculated key value will be100. Size goes to group with key100.Next sizes
98,10,5also will get key100and go to that group.For size
5454calculated key value will be1000000(it’s the first range which is greater that5454. So, new key is created, and size goes to group with key1000000.Etc.