C# Lists, updated to use LINQ

During 2006 I wrote a post about C# Lists. Of course, technology moves on, C# is no exception to that rule.

Whilst the examples I used in the 2006 blog entry still work today, LINQ heralds further levels of elegance and reduced the number of lines of code required to achieve the same results.

Here are the examples updated to use LINQ:

[code lang=”C#”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}

static void Main(string[] args)
{
Listpeople = new List();

people.Add(new Person(50, “Fred”));
people.Add(new Person(30, “John”));
people.Add(new Person(26, “Andrew”));
people.Add(new Person(24, “Xavier”));
people.Add(new Person(5, “Mark”));
people.Add(new Person(6, “Cameron”));

var unsorted = from p in people select p;
var sortedByAge = from p in people orderby p.age select p;
var theYoung = from p in people where p.age < 25 select p; var sortedByName = from p in people orderby p.name select p; foreach (var p1 in sortedByName) Console.WriteLine(string.Format("{0} {1}", p1.name,p1.age)); Console.ReadLine(); } } } [/code] On line 38, simply replace sortedByName with any of the other result sets. The use of LINQ in this simple example does demonstrate increased readability - the LINQ expressions are easier to understand than those present in the 2006 blog entry. If lines of code are your metric (and for some they are!), the LINQ version's conciseness does mean a reduction in the LOC count.