C# Linq 先按特定数字排序,然后按顺序显示所有其余部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9933888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq Order by a specific number first then show all rest in order
提问by vts
If i have a list of numbers:
如果我有一个数字列表:
1,2,3,4,5,6,7,8
and I want to order by a specific number and then show the rest. For example if i pick '3' the list should be:
我想按特定数字订购,然后显示其余部分。例如,如果我选择“3”,列表应该是:
3,1,2,4,5,6,7,8
Looking for linq and c#. Thank you
寻找 linq 和 c#。谢谢
采纳答案by Tim Schmelter
You can use a comparison in OrderByor ThenByto perform a conditional sorting.
您可以在OrderBy或 中使用比较ThenBy来执行条件排序。
list.OrderByDescending(i => i == 3).ThenBy(i => i);
I use OrderByDescendingbecause i want matching results first(trueis "higher" than false).
我使用OrderByDescending是因为我首先想要匹配结果(true“高于” false)。
回答by Arion
Maybe something like this:
也许是这样的:
List<int> ls=new List<int>{1,2,3,4,5,6,7,8};
int nbr=3;
var result= ls.OrderBy (l =>(l==nbr?int.MinValue:l));
回答by Joachim Isaksson
A couple of answers already sort the last few numbers (which may be correct since you're only showing an already sorted list). If you want the "unselected" numbers to be displayed in their original, not necessarily sorted orderinstead of sorted, you can instead do;
一些答案已经对最后几个数字进行了排序(这可能是正确的,因为您只显示了一个已经排序的列表)。如果您希望“未选择”的数字以其原始顺序显示,不一定是排序顺序而不是排序,您可以这样做;
int num = 3;
var result = list.Where(x => x == num).Concat(list.Where(x => x != num));
As @DuaneTheriot points out, IEnumerable's extension method OrderBydoes a stable sort and won't change the order of elements that have an equal key. In other words;
正如@DuaneTheriot 指出的那样,IEnumerable 的扩展方法 OrderBy执行稳定排序并且不会更改具有相等键的元素的顺序。换句话说;
var result = list.OrderBy(x => x != 3);
works just as well to sort 3 first and keep the order of all other elements.
也可以先对 3 进行排序并保持所有其他元素的顺序。
回答by Adrian Iftode
public static IEnumerable<T> TakeAndOrder<T>(this IEnumerable<T> items, Func<T, bool> f)
{
foreach ( var item in items.Where(f))
yield return item;
foreach (var item in items.Where(i=>!f(i)).OrderBy(i=>i))
yield return item;
}
var items = new [] {1, 4, 2, 5, 3};
items.TakeAndOrder(i=> i == 4);

