Sorting your C# objects with LINQ
Last modified: 09/01/2012
Jan 09
Suppose you create a Box class with some properties.
-
-
class Box
-
{
-
public string Name
-
{ get; set; }
-
-
public string Color
-
{ get; set; }
-
-
public string Label
-
{ get; set; }
-
-
public DateTime CreatedAt
-
{ get; set; }
-
-
public override string ToString()
-
{
-
return string.Format("[Name: {0}; Color: {1}; Label: {2}; CreatedAt: {3}]",
-
Name, Color, Label, CreatedAt);
-
}
-
}
Now you made some boxes and want to sort these boxes according its properties.
With LINQ this is quit easily done.
-
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
IEnumerable<Box> boxes = new List<Box>() {
-
new Box() { Name = "Bananas", Color = "Yellow", Label = "z",
-
CreatedAt = new DateTime(2010, 12, 9)},
-
new Box() { Name = "Pears", Color = "Green", Label = "x",
-
CreatedAt = new DateTime(2008, 05, 7)},
-
new Box() { Name = "Apples", Color = "Red", Label = "y",
-
CreatedAt = new DateTime(2010, 07, 1)},
-
};
-
-
Console.WriteLine("Unsorted list");
-
LoopList(boxes);
-
-
Console.WriteLine("\nList sorted on Name");
-
boxes = boxes.Select(item => item).OrderBy(item => item.Name);
-
LoopList(boxes);
-
-
Console.WriteLine("\nList sorted on Color");
-
boxes = boxes.Select(item => item).OrderBy(item => item.Color);
-
LoopList(boxes);
-
-
Console.WriteLine("\nList sorted on Label");
-
boxes = boxes.Select(item => item).OrderBy(item => item.Label);
-
LoopList(boxes);
-
-
Console.WriteLine("\nList sorted on CreationDate");
-
boxes = boxes.Select(item => item).OrderBy(item => item.CreatedAt);
-
LoopList(boxes);
-
-
Console.ReadKey();
-
}
-
-
static void LoopList(IEnumerable<Box> boxes)
-
{
-
foreach (var item in boxes)
-
{
-
Console.WriteLine(item);
-
}
-
}
-
}
-
-
Unsorted list
-
[Name: Bananas; Color: Yellow; Label: z; CreatedAt: 9/12/2010 0:00:00]
-
[Name: Pears; Color: Green; Label: x; CreatedAt: 7/05/2008 0:00:00]
-
[Name: Apples; Color: Red; Label: y; CreatedAt: 1/07/2010 0:00:00]
-
-
List sorted on Name
-
[Name: Apples; Color: Red; Label: y; CreatedAt: 1/07/2010 0:00:00]
-
[Name: Bananas; Color: Yellow; Label: z; CreatedAt: 9/12/2010 0:00:00]
-
[Name: Pears; Color: Green; Label: x; CreatedAt: 7/05/2008 0:00:00]
-
-
List sorted on Color
-
[Name: Pears; Color: Green; Label: x; CreatedAt: 7/05/2008 0:00:00]
-
[Name: Apples; Color: Red; Label: y; CreatedAt: 1/07/2010 0:00:00]
-
[Name: Bananas; Color: Yellow; Label: z; CreatedAt: 9/12/2010 0:00:00]
-
-
List sorted on Label
-
[Name: Pears; Color: Green; Label: x; CreatedAt: 7/05/2008 0:00:00]
-
[Name: Apples; Color: Red; Label: y; CreatedAt: 1/07/2010 0:00:00]
-
[Name: Bananas; Color: Yellow; Label: z; CreatedAt: 9/12/2010 0:00:00]
-
-
List sorted on CreationDate
-
[Name: Pears; Color: Green; Label: x; CreatedAt: 7/05/2008 0:00:00]
-
[Name: Apples; Color: Red; Label: y; CreatedAt: 1/07/2010 0:00:00]
-
[Name: Bananas; Color: Yellow; Label: z; CreatedAt: 9/12/2010 0:00:00]
[?]
RSS