Adventures in C# – Sort An Object With Linq

By | August 8, 2017

Linq and lambda expressions to sort an object array in just a few lines

I’ve seen some questions in technical forums concerning similar functionality so hopefully this article will be helpful to someone out there.QualTech Software Development Services | QualTech360DoNet

This article discusses a short c# console project demonstrating how in just a few lines of code you can sort an object array. You can use the sorted object array to for example add it to a UI control.

You can download the Visual Studio solution here.

static void Main( string[] args )
{
Menu[] menuItems = null;

menuItems = MenuList();

menuItems = menuItems.OrderBy( x => x.Item ).ToArray();

foreach( Menu item in menuItems )
{
Console.WriteLine( string.Format( “Item: {0} Price: {1} Item Type: {2}”, item.Item, item.Price, item.ItemType ) );
}

Console.WriteLine(“Enter to end.”);
Console.Read();
}

Better then trying to explain what the code does is to run the project in debug mode so you can inspect the variables and see for yourself what’s happening while the code executes.

Everything pretty much happens in the line menuItems = menuItems.OrderBy( x => x.Item ).ToArray(). The variable menuItems has an array of Menu objects. In this line we are instructing the code to use the Item property of the Menu object and sort the array based on the content of that property.

The MenuList() is the method that instantiates the array as shown in the code below:

public static Menu[] MenuList()
{
List menuItems = null;

menuItems = menuItems.OrderBy( x => x.Item ).ToArray();

menuItems.Add( new Menu() { Item = “Lamb Ribs”, Price = 8.00, ItemType = “Starter” } );
menuItems.Add( new Menu() { Item = “HSP”, Price = 7.00, ItemType = “Starter” } );
menuItems.Add( new Menu() { Item = “Bread”, Price = 3.00, ItemType = “Starter” } );

return menuItems.ToArray();

}

QualTech .Net Software Development Services | QualTech360DotNet

A contribution of QualTech’s software engineering team.

#QualTech360Care, #QualTech360Development, #QualTech360Solutions

Leave a Reply