Sorting an Array with a Lambda Expression

Let's say you have the following listbox in XAML


<
UserControl x:Class="SortingAListBox.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<ListBox ItemsSource="{Binding Items}" Width="400">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Background="{Binding ColorValue}" HorizontalAlignment="Stretch" Width="400">
<TextBlock Text="{Binding Name}" FontWeight="Medium" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</
UserControl>

And you have the following ViewModel that is bound to it:


using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Windows.Media;
namespace
SortingAListBox
{
public class ColorItem
{
public string Name { get; set;}
public string ColorValue { get; set;}
public ColorItem(string name, Color val)
{
Name = name;
ColorValue = val.ToString();
}
}
public class ListBoxViewModel
{
public ListBoxViewModel()
{
Items =
new List<ColorItem>();
PopulateItems();
}
private void PopulateItems()
{
Items.Add(
new ColorItem("Bill", Colors.Yellow));
Items.Add(
new ColorItem("Bob", Colors.Gray));
Items.Add(
new ColorItem("Jim", Colors.Red));
Items.Add(
new ColorItem("Anne", Color.FromArgb(255, 255, 128, 128)));
}
public List<ColorItem> Items
{
get;
set;
}
}
}


You want to display your list box as a list of sorted items, sorted by color item's Name.  How would you go about doing it?

One way is to use the System.Array class's  Sort method.   The sort method either requires that ColorItem implement IComparable, or you pass in a function that tells the ColorItem how to sort.  With Lambda expressions you can pass a function quite easily to the Sort method on an array.  Let's alter our constructor so it sorts the list.


public ListBoxViewModel()
{
Items =
new List<ColorItem>();
PopulateItems();
var array = Items.ToArray();
Array.Sort(array, (o1, o2) => o1.Name.CompareTo(o2.Name));
Items = array.ToList();
}
That's all there is to it, just create a lambda expression for the 2nd parameter of the Sort method that sorts on the Name property of the ColorItem.






Ebook Download
View all
Learn
View all