C# 对 ObservableCollection 进行排序

C# sort an ObservableCollection

快速提问,因为我试过的其他方法都不起作用。

我有以下代码:

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

Colors = new ObservableCollection<Lines>();

_lines.ItemsSource = Colors;

然后我使用循环为 collection 添加颜色。我使用一个按钮来添加带有 lineId.

的新颜色

这些颜色具有 lineID (int),结果如下:

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

使用我的代码可能会出现顺序错误的情况。我希望它是红色,而不是将黄色作为我的最后一种颜色。所以我必须对我的列表进行排序。

但这是我的问题,我尝试了以下三个选项但它们都没有用:

_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))

有人知道我能做什么吗?

这可以通过按 Id 排序来实现。

下面是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

    }

xaml中的代码:

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