简体   繁体   English

使用LINQ在C#中对列表进行排序

[英]Sort list in C# with LINQ

I want to sort a list in C#. 我想在C#中对列表进行排序。

Like where structure property AVC goes to true then show them first then AVC goes to false. 就像结构属性AVC转到true那样先显示它们然后AVC变为false。 Are any way to do this in C# LINQ? 有没有办法在C#LINQ中执行此操作?

Well, the simplest way using LINQ would be something like this: 那么,使用LINQ最简单的方法是这样的:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or 要么

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true , but the first form makes it clearer IMO, because everyone knows that 0 < 1 . 相信 bool值的自然排序是false < true ,但第一种形式使IMO更清晰,因为每个人都知道0 < 1

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. 请注意,这不会对原始列表本身进行排序 - 它将创建一个新列表,并将引用分配回list变量。 If you want to sort in place, you should use the List<T>.Sort method. 如果要进行排序,则应使用List<T>.Sort方法。

Like this? 像这样?

In LINQ: 在LINQ中:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place: 或就地:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true. 正如Jon Skeet所说,这里的诀窍是知道false被认为是“小”而不是true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces. 如果您发现在代码中的许多不同位置执行这些排序操作,您可能希望使用类型Foo来实现IComparable<Foo>IComparable接口。

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. 我假设你希望它们按其他东西排序,以便在AVC相同的所有项目之间获得一致的排序。 For example by name: 例如按名称:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM