PROWAREtech

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

.NET: Compound Statements, Select, Any and OrderBy - Language Integrated Query (LINQ)

Language Integrated Query (LINQ) Tutorial - Page 2.

Compound from Statements

Here is an example that begins to show the power of LINQ. It uses a compound from statement to access a sequenced member of an object. The select clause is being used to transform the result into a sequence of integers.

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 int Age { get; set; }
		public string[] Cars { get; private set; }

		public Person(string LastName = null, string FirstName = null, int Age = 0, IEnumerable<string> Cars = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Age = Age;
			List<string> cars = new List<string>();
			foreach(string car in Cars)
			{
				cars.Add(car);
			}
			this.Cars = cars.ToArray();
		}
		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() + " - " + Age.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", 35, new string[] { "Civic", "Smart Car" }));
				students.Add(new Person("Crabtree", "Glenn", 30, new string[] { "Element" }));
				students.Add(new Person("Kellerman", "Calandra", 30, new string[] { "F150", "Civic" }));
				students.Add(new Person("Chairez", "Judy", 27, new string[] { "Outback", "Element" }));
				students.Add(new Person("Santore", "Cari", 42, new string[] { "F250" }));
				students.Add(new Person("Barnaby", "Emelda", 27, new string[] { "Cayenne" }));
				students.Add(new Person("Beeler", "Rufina", 22, new string[] { "320i", "911" }));
				students.Add(new Person("Barreiro", "Jessia", 31, new string[] { "WRX", "Civic", "Ridgeline" }));
				students.Add(new Person("Kummer", "Bebe", 30, new string[] { "F150" }));
				students.Add(new Person("Sexson", "Aleida", 25, new string[] { "Outback" }));
				students.Add(new Person("Ansell", "Freida", 44, new string[] { "Element" }));
				students.Add(new Person("Eriksson", "Jae", 49, new string[] { "Pilot", "Accord" }));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = from p in Classroom.GetAttendance()
						where p.Age < 40
						select p.Age; // select just the Age member
			foreach (int age in query)
			{
				Console.WriteLine(age);
			}

			Console.WriteLine("\r\nCivic Owners:");

			// use a compound from statement to access a sequenced member of an object
			var civicQuery = from p in Classroom.GetAttendance()
							 from c in p.Cars
							 where c == "Civic"
							 select p;
			foreach (Person obj in civicQuery)
			{
				Console.WriteLine("{0:N}", obj);
			}

			Console.WriteLine("\r\nF150 Owners:");

			var f150Query = from p in Classroom.GetAttendance()
							 from c in p.Cars
							 where c == "F150"
							 select p;
			foreach (Person obj in f150Query)
			{
				Console.WriteLine("{0:N}", obj);
			}
		}
	}
}
Using Lambda with LINQ Methods Select(), Where() and Any()
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 int Age { get; set; }
		public string[] Cars { get; private set; }

		public Person(string LastName = null, string FirstName = null, int Age = 0, IEnumerable<string> Cars = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Age = Age;
			List<string> cars = new List<string>();
			foreach(string car in Cars)
			{
				cars.Add(car);
			}
			this.Cars = cars.ToArray();
		}
		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() + " - " + Age.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", 35, new string[] { "Civic", "Smart Car" }));
				students.Add(new Person("Crabtree", "Glenn", 30, new string[] { "Element" }));
				students.Add(new Person("Kellerman", "Calandra", 30, new string[] { "F150", "Civic" }));
				students.Add(new Person("Chairez", "Judy", 27, new string[] { "Outback", "Element" }));
				students.Add(new Person("Santore", "Cari", 42, new string[] { "F250" }));
				students.Add(new Person("Barnaby", "Emelda", 27, new string[] { "Cayenne" }));
				students.Add(new Person("Beeler", "Rufina", 22, new string[] { "320i", "911" }));
				students.Add(new Person("Barreiro", "Jessia", 31, new string[] { "WRX", "Civic", "Ridgeline" }));
				students.Add(new Person("Kummer", "Bebe", 30, new string[] { "F150" }));
				students.Add(new Person("Sexson", "Aleida", 25, new string[] { "Outback" }));
				students.Add(new Person("Ansell", "Freida", 44, new string[] { "Element" }));
				students.Add(new Person("Eriksson", "Jae", 49, new string[] { "Pilot", "Accord" }));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = Classroom.GetAttendance().Select(p => p.Age).Where(a => a < 40);
			foreach (int age in query)
			{
				Console.WriteLine(age);
			}

			Console.WriteLine("\r\nCivic Owners:");

			// use a compound from statement to access a sequenced member of an object
			var civicQuery = Classroom.GetAttendance().Where(p => p.Cars.Any(c => c == "Civic"));
			foreach (Person obj in civicQuery)
			{
				Console.WriteLine("{0:N}", obj);
			}

			Console.WriteLine("\r\nF150 Owners:");

			var f150Query = Classroom.GetAttendance().Where(p => p.Cars.Any(c => c == "F150"));
			foreach (Person obj in f150Query)
			{
				Console.WriteLine("{0:N}", obj);
			}
		}
	}
}

orderby Clause

This demonstrates that the orderby clause can sort by two or more fields. First it sorts by age (descending) then by last name and first name.

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 int Age { get; set; }
		public string[] Cars { get; private set; }

		public Person(string LastName = null, string FirstName = null, int Age = 0, IEnumerable<string> Cars = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Age = Age;
			List<string> cars = new List<string>();
			foreach(string car in Cars)
			{
				cars.Add(car);
			}
			this.Cars = cars.ToArray();
		}
		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() + " - " + Age.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", 35, new string[] { "Civic", "Smart Car" }));
				students.Add(new Person("Crabtree", "Glenn", 30, new string[] { "Element" }));
				students.Add(new Person("Kellerman", "Calandra", 30, new string[] { "F150", "Civic" }));
				students.Add(new Person("Chairez", "Judy", 27, new string[] { "Outback", "Element" }));
				students.Add(new Person("Santore", "Cari", 42, new string[] { "F250" }));
				students.Add(new Person("Barnaby", "Emelda", 27, new string[] { "Cayenne" }));
				students.Add(new Person("Beeler", "Rufina", 22, new string[] { "320i", "911" }));
				students.Add(new Person("Barreiro", "Jessia", 31, new string[] { "WRX", "Civic", "Ridgeline" }));
				students.Add(new Person("Kummer", "Bebe", 30, new string[] { "F150" }));
				students.Add(new Person("Sexson", "Aleida", 25, new string[] { "Outback" }));
				students.Add(new Person("Ansell", "Freida", 44, new string[] { "Element" }));
				students.Add(new Person("Eriksson", "Jae", 49, new string[] { "Pilot", "Accord" }));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = from p in Classroom.GetAttendance()
						where p.Age < 40
						orderby p.Age descending
						select p;
			foreach (Person obj in query)
			{
				Console.WriteLine("{0:A}", obj);
			}

			Console.WriteLine("\r\nCivic Owners:");

			// use a compound from statement to access a sequenced member of an object
			var civicQuery = from p in Classroom.GetAttendance()
							 from c in p.Cars
							 where c == "Civic"
							 orderby p.LastName, p.FirstName // sort by two fields
							 select p;
			foreach (Person obj in civicQuery)
			{
				Console.WriteLine("{0:N}", obj);
			}

			Console.WriteLine("\r\nF150 Owners:");

			var f150Query = from p in Classroom.GetAttendance()
							 from c in p.Cars
							 where c == "F150"
							 orderby p.LastName, p.FirstName // sort by two fields
							 select p;
			foreach (Person obj in f150Query)
			{
				Console.WriteLine("{0:N}", obj);
			}
		}
	}
}

Program output:

Holman, Kaylee - 35
Barreiro, Jessia - 31
Kummer, Bebe - 30
Kellerman, Calandra - 30
Crabtree, Glenn - 30
Barnaby, Emelda - 27
Chairez, Judy - 27
Sexson, Aleida - 25
Beeler, Rufina - 22


Civic Owners:
Barreiro, Jessia
Holman, Kaylee
Kellerman, Calandra

F150 Owners:
Kellerman, Calandra
Kummer, Bebe
Using Lambda with the LINQ Methods Where(), Any(), OrderBy() and ThenBy()

The ThenByDescending() method is not use but also available.

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 int Age { get; set; }
		public string[] Cars { get; private set; }

		public Person(string LastName = null, string FirstName = null, int Age = 0, IEnumerable<string> Cars = null)
		{
			this.LastName = LastName;
			this.FirstName = FirstName;
			this.Age = Age;
			List<string> cars = new List<string>();
			foreach(string car in Cars)
			{
				cars.Add(car);
			}
			this.Cars = cars.ToArray();
		}
		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() + " - " + Age.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", 35, new string[] { "Civic", "Smart Car" }));
				students.Add(new Person("Crabtree", "Glenn", 30, new string[] { "Element" }));
				students.Add(new Person("Kellerman", "Calandra", 30, new string[] { "F150", "Civic" }));
				students.Add(new Person("Chairez", "Judy", 27, new string[] { "Outback", "Element" }));
				students.Add(new Person("Santore", "Cari", 42, new string[] { "F250" }));
				students.Add(new Person("Barnaby", "Emelda", 27, new string[] { "Cayenne" }));
				students.Add(new Person("Beeler", "Rufina", 22, new string[] { "320i", "911" }));
				students.Add(new Person("Barreiro", "Jessia", 31, new string[] { "WRX", "Civic", "Ridgeline" }));
				students.Add(new Person("Kummer", "Bebe", 30, new string[] { "F150" }));
				students.Add(new Person("Sexson", "Aleida", 25, new string[] { "Outback" }));
				students.Add(new Person("Ansell", "Freida", 44, new string[] { "Element" }));
				students.Add(new Person("Eriksson", "Jae", 49, new string[] { "Pilot", "Accord" }));
			}
			return students;
		}
	}

	class Program
	{
		static void Main()
		{
			var query = Classroom.GetAttendance().Where(p => p.Age < 40).OrderByDescending(p => p.Age);
			foreach (Person obj in query)
			{
				Console.WriteLine("{0:A}", obj);
			}

			Console.WriteLine("\r\nCivic Owners:");

			// use a compound from statement to access a sequenced member of an object
			var civicQuery = Classroom.GetAttendance().Where(p => p.Cars.Any(c => c == "Civic")).OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
			foreach (Person obj in civicQuery)
			{
				Console.WriteLine("{0:N}", obj);
			}

			Console.WriteLine("\r\nF150 Owners:");

			var f150Query = Classroom.GetAttendance().Where(p => p.Cars.Any(c => c == "F150")).OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
			foreach (Person obj in f150Query)
			{
				Console.WriteLine("{0:N}", obj);
			}
		}
	}
}

Program output:

Holman, Kaylee - 35
Barreiro, Jessia - 31
Kummer, Bebe - 30
Kellerman, Calandra - 30
Crabtree, Glenn - 30
Barnaby, Emelda - 27
Chairez, Judy - 27
Sexson, Aleida - 25
Beeler, Rufina - 22


Civic Owners:
Barreiro, Jessia
Holman, Kaylee
Kellerman, Calandra

F150 Owners:
Kellerman, Calandra
Kummer, Bebe
<<<[Page 2 of 7]>>>

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