C # 中使用 LINQ 的排序列表

我想用 C # 对列表进行排序。

比如结构属性 AVC 变为 true 然后先显示结构属性,然后 AVC 变为 false。在 C # LINQ 中有什么方法可以做到这一点吗?

228803 次浏览

Well, the simplest way using LINQ would be something like this:

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.

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. If you want to sort in place, you should use the List<T>.Sort method.

Like this?

In 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.

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.

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

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

A syntax alternative for the accepted answer:

list = from item in list
orderby item.AVC
select item;

Keep in mind that "list" is now an IEnumerable object and not a List one.