ToLookup C# with Example
ToLookup returns a data structure that allows indexing. It is an extension method. It produces an ILookup instance that can be indexed or enumerated using a foreach-loop. The entries are combined into groupings at each key. - dotnetperls string[] array = { "one", "two", "three" }; //create lookup using string length as key var lookup = array.ToLookup(item => item.Length); //join the values whose lengths are 3 Console.WriteLine(string.Join(",",lookup[3])); //output: one,two Another Example: int[] array = { 1,2,3,4,5,6,7,8 }; //generate lookup for odd even numbers (keys will be 0 and 1) var lookup = array.ToLookup(item => item % 2); //print even numbers after joining Console.WriteLine(string.Join(",",lookup[0])); //output: 2,4,6,8 //print odd numbers after joining Console.WriteLine(string.Join(",",lookup[1])); //output: 1,3,5,7