Group query results in LINQ



Grouping is one of the most powerful capabilities of LINQ. The following examples show how to group data in various ways:
By a single property.
By the first letter of a string property.
By a computed numeric range.
By Boolean predicate or another expression.
By a compound key.

using System;
using System. Linq;

namespace CSharpLINQ
{
    class SimpleQuery
    {
		static void Main( )
		{
			var students = new[] // Array of objects of an anonymous type
			{
				new { LName="Mishra", FName="Kuldeep", Age=31 },
				new { LName="Sharma", FName="Ramesh", Age=20 },
				new { LName="Sharma", FName="Manoj", Age=21 },
				new { LName="Mishra", FName="Rajesh", Age=45 },
				new { LName="Soni", FName="Suresh", Age=35 },
				new { LName="Goyal", FName="Dinesh", Age=15},
				new { LName="Mishra", FName="Jignesh", Age=31 },
				new { LName="Sharma", FName="Mrigesh", Age=20 },
				new { LName="Verma", FName="Prakash", Age=21 },
				new { LName="Mishra", FName="Aakash", Age=45 },
				new { LName="Soni", FName="Dinkar", Age=35 },
				new { LName="Goyal", FName="Divakar", Age=15},
				new { LName="Goyal", FName="Bhaskar", Age=31 },
				new { LName="Sharma", FName="Tanuj", Age=20 },
				new { LName="Verma", FName="Anuj", Age=21 },
				new { LName="Goyal", FName="Dhanush", Age=45 },
				new { LName="Soni", FName="Mulri", Age=35 },
				new { LName="Goyal", FName="Manohar", Age=15},
				new { LName="Mishra", FName="Sohan", Age=31 },
				new { LName="Sharma", FName="Ram", Age=20 },
				new { LName="Soni", FName="Mohan", Age=21 },
				new { LName="Soni", FName="Rohan", Age=45 },
				new { LName="Soni", FName="Rahul", Age=35 },
				new { LName="Goyal", FName="Rohit", Age=15}
			};

			var query = from student in students group student by student.LName;
			
			foreach (var student in query)
			{
				Console.WriteLine("\nStudents grouped by Cast: " + student.Key);
				foreach (var q in student)
					Console.WriteLine("        {0},  Age: {1}", q.FName, q.Age);
			}
		}
    }
}

0 Comment's

Comment Form

Submit Comment