Home > Enterprise >  C# sort an ObservableCollection
C# sort an ObservableCollection

Time:03-15

Quick question since other methods I tried didn't work.

I have the following code:

public ObservableCollection<Lines> Colors { get; set; }

Colors = new ObservableCollection<Lines>();

_lines.ItemsSource = Colors;

Then I use a loop to add colors to my collection. I use a button to add a new color with a lineId.

These colors have a lineID (int) which results in the following:

Blue with lineId = 1.
Red with lineId = 2.
Green with lineId = 4.
Yellow with lineId = 3.

With my code it can happen that they are in the wrong order. Instead of having Yellow as my last color, I want it to be Red. So I have to sort my list.

But here is my problem, I tried the following three options but they didn't work:

_lines.ItemsSource = Colors.OrderBy(j => j.lineId) ;

Colors = new ObservableCollection<Lines>(Colors.OrderBy(j => j .lineId));

foreach (var item in Colors.OrderBy(j => j.lineId))

Does anyone know what I can do?

CodePudding user response:

This can be achieved by sort by Id.

Below is the code in page.cs:

    public ObservableCollection<Lines> Colors { get; set; }

    public TestPage()
    {
        InitializeComponent();
        Colors = new ObservableCollection<Lines>();
        Colors.Add(new Lines() { Id = 1, Color = "blue" });
        Colors.Add(new Lines() { Id = 2, Color = "red" });
        Colors.Add(new Lines() { Id = 4, Color = "green" });
        Colors.Add(new Lines() { Id = 3, Color = "yellow" });

        List<Lines> list = Colors.ToList();//convert to list
        list.Sort((l, r) => l.Id.CompareTo(r.Id));//sort by list.Id
        Colors = new ObservableCollection<Lines>(list);//revert back to observablecollection
        mytest.ItemsSource = Colors;//binding to xaml

    }

code in xaml:

    <ListView x:Name="mytest">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Color}"></Label>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
  • Related