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.

4 thoughts on “C# Lists, updated to use LINQ”

  1. Hi Craig,

    Thanks very much for that, very useful indeed – I could find very few resources online for this. It can be hard starting out in C# from PHP etc., especially if all you want are simple examples on how to do stuff like this optimally!

    @chris_alexander

  2. Just thought I would point out that LINQ Querys are chainable. If you wanted your young people sorted by age you could just replace people with sortedByAge

    var theYoungSorted = from p in sortedByAge where p.age < YOUNG_LIMIT select p;

    This is particularly valuable when you want to build a LINQ query based on user selected values in GUI widgets.

Comments are closed.