Sunday, March 28, 2010

Multiple Order By in LINQ

This is how you do it:
List orderedItems = items.OrderBy(o => o.Group).ThenBy(o => o.Name).ToList();

Example Code:
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLinqOrderBy
{


class SomeItem
{
private String _group;
private String _name;

public SomeItem(String group, String name)
{
this._group = group;
this._name = name;
}

public String Group
{
get { return _group; }
set { _group = value; }
}

public String Name
{
get { return _name; }
set { _name = value; }
}
}
}

Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLinqOrderBy
{
class Program
{
static void Main(string[] args)
{
List items = new List();

items.Add(new SomeItem("group 1","All"));
items.Add(new SomeItem("group 1","How"));
items.Add(new SomeItem("group 1","Are"));
items.Add(new SomeItem("group 1","You"));
items.Add(new SomeItem("group 1","Today?"));
items.Add(new SomeItem("group 1", "Cat"));
items.Add(new SomeItem("group 1", "Ball"));

items.Add(new SomeItem("group 2", "All"));
items.Add(new SomeItem("group 2", "How"));
items.Add(new SomeItem("group 2", "Are"));
items.Add(new SomeItem("group 2", "You"));
items.Add(new SomeItem("group 2", "Today?"));
items.Add(new SomeItem("group 2", "Cat"));
items.Add(new SomeItem("group 2", "Ball"));

items.Add(new SomeItem("group 3", "All"));
items.Add(new SomeItem("group 3", "How"));
items.Add(new SomeItem("group 3", "Are"));
items.Add(new SomeItem("group 3", "You"));
items.Add(new SomeItem("group 3", "Today?"));
items.Add(new SomeItem("group 3", "Cat"));
items.Add(new SomeItem("group 3", "Ball"));

List orderedItems = items.OrderBy(o => o.Group).ThenBy(o => o.Name).ToList();

}
}
}


Thanks to Jonas Stawski

No comments: