PROWAREtech

articles » current » dot-net » tutorial » linq » page-4

.NET: Language Integrated Query (LINQ) - Page 4

Group Clause, GroupBy.

The group Clause

The group clause can be used to group results based on a key.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqExample
{
	[Serializable]
	public class Person : IComparable<Person>, IFormattable
	{
		public string LastName { get; set; }
		public string FirstName { get; set; }
		public string Country { get; set; }

		public Person(string LastName = null, string FirstName = null, string Country = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Country = Country;
		}
		public int CompareTo(Person person)
		{
			if (person == null)
				throw new ArgumentNullException("person");
			return LastName.CompareTo(person.LastName);
		}
		public override string ToString()
		{
			return LastName + ", " + FirstName;
		}
		public string ToString(string format)
		{
			return ToString(format, null);
		}
		public string ToString(string format, IFormatProvider FormatProvider)
		{
			switch (format)
			{
				case null:
				case "N": // return full name
					return ToString();
				case "L": // return last name
					return LastName;
				case "F": // return first name
					return FirstName;
				case "A": // return all information
					return ToString() + " - " + Country.ToString();
				default:
					throw new FormatException("Format " + format + " unsupported");
			}
		}
	}

	public static class Classroom
	{
		private static List<Person> students;

		public static IList<Person> GetAttendance()
		{
			if (students == null)
			{
				students = new List<Person>();
				students.Add(new Person("Holman", "Kaylee", "Holland"));
				students.Add(new Person("Crabtree", "Glenn", "France"));
				students.Add(new Person("Kellerman", "Calandra", "United States"));
				students.Add(new Person("Chairez", "Judy", "France"));
				students.Add(new Person("Santore", "Cari", "Germany"));
				students.Add(new Person("Barnaby", "Emelda", "Germany"));
				students.Add(new Person("Beeler", "Rufina", "Britain"));
				students.Add(new Person("Barreiro", "Jessia", "United States"));
				students.Add(new Person("Kummer", "Bebe", "Brazil"));
				students.Add(new Person("Sexson", "Aleida", "Italy"));
				students.Add(new Person("Ansell", "Freida", "United States"));
				students.Add(new Person("Eriksson", "Jae", "Belgium"));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = from p in Classroom.GetAttendance()
						group p by p.Country into g
						orderby g.Count() descending
						where g.Count() > 1
						select new
						{
							Country = g.Key,
							Count = g.Count()
						};
			foreach (var obj in query)
			{
				Console.WriteLine("{0, -15} {1}", obj.Country, obj.Count);
			}
		}
	}
}
United States   3
France          2
Germany         2
Using Lambda with LINQ Methods GroupBy(), OrderByDescending(), Where(), Count() and Select()
using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqExample
{
	[Serializable]
	public class Person : IComparable<Person>, IFormattable
	{
		public string LastName { get; set; }
		public string FirstName { get; set; }
		public string Country { get; set; }

		public Person(string LastName = null, string FirstName = null, string Country = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Country = Country;
		}
		public int CompareTo(Person person)
		{
			if (person == null)
				throw new ArgumentNullException("person");
			return LastName.CompareTo(person.LastName);
		}
		public override string ToString()
		{
			return LastName + ", " + FirstName;
		}
		public string ToString(string format)
		{
			return ToString(format, null);
		}
		public string ToString(string format, IFormatProvider FormatProvider)
		{
			switch (format)
			{
				case null:
				case "N": // return full name
					return ToString();
				case "L": // return last name
					return LastName;
				case "F": // return first name
					return FirstName;
				case "A": // return all information
					return ToString() + " - " + Country.ToString();
				default:
					throw new FormatException("Format " + format + " unsupported");
			}
		}
	}

	public static class Classroom
	{
		private static List<Person> students;

		public static IList<Person> GetAttendance()
		{
			if (students == null)
			{
				students = new List<Person>();
				students.Add(new Person("Holman", "Kaylee", "Holland"));
				students.Add(new Person("Crabtree", "Glenn", "France"));
				students.Add(new Person("Kellerman", "Calandra", "United States"));
				students.Add(new Person("Chairez", "Judy", "France"));
				students.Add(new Person("Santore", "Cari", "Germany"));
				students.Add(new Person("Barnaby", "Emelda", "Germany"));
				students.Add(new Person("Beeler", "Rufina", "Britain"));
				students.Add(new Person("Barreiro", "Jessia", "United States"));
				students.Add(new Person("Kummer", "Bebe", "Brazil"));
				students.Add(new Person("Sexson", "Aleida", "Italy"));
				students.Add(new Person("Ansell", "Freida", "United States"));
				students.Add(new Person("Eriksson", "Jae", "Belgium"));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = Classroom.GetAttendance().GroupBy(p => p.Country).OrderByDescending(g => g.Count()).Where(g => g.Count() > 1).Select(g => new { Country = g.Key, Count = g.Count() });
			foreach (var obj in query)
			{
				Console.WriteLine("{0, -15} {1}", obj.Country, obj.Count);
			}
		}
	}
}

Nested Objects

When the grouped object contains nested sequences, just modify the select clause.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqExample
{
	[Serializable]
	public class Person : IComparable<Person>, IFormattable
	{
		public string LastName { get; set; }
		public string FirstName { get; set; }
		public string Country { get; set; }

		public Person(string LastName = null, string FirstName = null, string Country = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Country = Country;
		}
		public int CompareTo(Person person)
		{
			if (person == null)
				throw new ArgumentNullException("person");
			return LastName.CompareTo(person.LastName);
		}
		public override string ToString()
		{
			return LastName + ", " + FirstName;
		}
		public string ToString(string format)
		{
			return ToString(format, null);
		}
		public string ToString(string format, IFormatProvider FormatProvider)
		{
			switch (format)
			{
				case null:
				case "N": // return full name
					return ToString();
				case "L": // return last name
					return LastName;
				case "F": // return first name
					return FirstName;
				case "A": // return all information
					return ToString() + " - " + Country.ToString();
				default:
					throw new FormatException("Format " + format + " unsupported");
			}
		}
	}

	public static class Classroom
	{
		private static List<Person> students;

		public static IList<Person> GetAttendance()
		{
			if (students == null)
			{
				students = new List<Person>();
				students.Add(new Person("Holman", "Kaylee", "Holland"));
				students.Add(new Person("Crabtree", "Glenn", "France"));
				students.Add(new Person("Kellerman", "Calandra", "United States"));
				students.Add(new Person("Chairez", "Judy", "France"));
				students.Add(new Person("Santore", "Cari", "Germany"));
				students.Add(new Person("Barnaby", "Emelda", "Germany"));
				students.Add(new Person("Beeler", "Rufina", "Britain"));
				students.Add(new Person("Barreiro", "Jessia", "United States"));
				students.Add(new Person("Kummer", "Bebe", "Brazil"));
				students.Add(new Person("Sexson", "Aleida", "Italy"));
				students.Add(new Person("Ansell", "Freida", "United States"));
				students.Add(new Person("Eriksson", "Jae", "Belgium"));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = from p in Classroom.GetAttendance()
						group p by p.Country into g
						orderby g.Count() descending
						where g.Count() > 1
						select new
						{
							Country = g.Key,
							Count = g.Count(),
							Students = from p2 in g
										 orderby p2.LastName
										 select p2.LastName + ", " + p2.FirstName
						};
			foreach (var obj in query)
			{
				Console.WriteLine("{0, -15} {1}", obj.Country, obj.Count);
				foreach (string s in obj.Students)
				{
					Console.WriteLine("\t" + s);
				}
			}
		}
	}
}
United States   3
        Ansell, Freida
        Barreiro, Jessia
        Kellerman, Calandra
France          2
        Chairez, Judy
        Crabtree, Glenn
Germany         2
        Barnaby, Emelda
        Santore, Cari
With LINQ Methods GroupBy(), OrderByDescending(), Where() and Select()
using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqExample
{
	[Serializable]
	public class Person : IComparable<Person>, IFormattable
	{
		public string LastName { get; set; }
		public string FirstName { get; set; }
		public string Country { get; set; }

		public Person(string LastName = null, string FirstName = null, string Country = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Country = Country;
		}
		public int CompareTo(Person person)
		{
			if (person == null)
				throw new ArgumentNullException("person");
			return LastName.CompareTo(person.LastName);
		}
		public override string ToString()
		{
			return LastName + ", " + FirstName;
		}
		public string ToString(string format)
		{
			return ToString(format, null);
		}
		public string ToString(string format, IFormatProvider FormatProvider)
		{
			switch (format)
			{
				case null:
				case "N": // return full name
					return ToString();
				case "L": // return last name
					return LastName;
				case "F": // return first name
					return FirstName;
				case "A": // return all information
					return ToString() + " - " + Country.ToString();
				default:
					throw new FormatException("Format " + format + " unsupported");
			}
		}
	}

	public static class Classroom
	{
		private static List<Person> students;

		public static IList<Person> GetAttendance()
		{
			if (students == null)
			{
				students = new List<Person>();
				students.Add(new Person("Holman", "Kaylee", "Holland"));
				students.Add(new Person("Crabtree", "Glenn", "France"));
				students.Add(new Person("Kellerman", "Calandra", "United States"));
				students.Add(new Person("Chairez", "Judy", "France"));
				students.Add(new Person("Santore", "Cari", "Germany"));
				students.Add(new Person("Barnaby", "Emelda", "Germany"));
				students.Add(new Person("Beeler", "Rufina", "Britain"));
				students.Add(new Person("Barreiro", "Jessia", "United States"));
				students.Add(new Person("Kummer", "Bebe", "Brazil"));
				students.Add(new Person("Sexson", "Aleida", "Italy"));
				students.Add(new Person("Ansell", "Freida", "United States"));
				students.Add(new Person("Eriksson", "Jae", "Belgium"));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = Classroom.GetAttendance()
						.GroupBy(p => p.Country)
						.OrderByDescending(g => g.Count())
						.Where(g => g.Count() > 1)
						.Select(g => new { Country = g.Key, Count = g.Count(), Students = g.OrderBy(g => g.LastName).Select(s => s.LastName + ", " + s.FirstName) });
			foreach (var obj in query)
			{
				Console.WriteLine("{0, -15} {1}", obj.Country, obj.Count);
				foreach (string s in obj.Students)
				{
					Console.WriteLine("\t" + s);
				}
			}
		}
	}
}
<<<[Page 4 of 7]>>>

PROWAREtech

Hello there! How can I help you today?
Ask any question
This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE