Group Clause: Advance LINQ Part - 1

Explanation

  1. string str = "thisistestingfileforthetrainees";  
  2. var x = from a in str  
  3. group a by a into g  
  4. select g;  
  5.   
  6. foreach(var item in x)  
  7. {  
  8.    Console.WriteLine(item.Key + "\t" + item.Count());  
  9. }  
This program used to display character and frequency of character from given string.

Explanation
  1. int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 6, 2 };  
  2. var x = from a in num  
  3. group a by a into g  
  4. select g;  
  5. foreach (var item in x)  
  6. {  
  7.    Console.WriteLine(item.Key + "\t" + item.Count());  
  8. }  
This program used to display number and frequency of number from given array.

Explanation
  1. int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 6, 2 };  
  2. var x = from a in num  
  3. group a by a into g  
  4. select g;  
  5. foreach (var item in x)  
  6. {  
  7.    Console.WriteLine(item.Key + "\t" + item.Sum()+"\t"+item.Count());  
  8. }  
This program used to display number, multiplication of number with number frequency and frequency of number from given array.

Note

Group clause used to create a group of values with key. Key contain unique data and can perform operation on value as getting count operation or getting sum operation etc.