我想订购一个字符串列表,但列表中的一个字符串应始终位于开头且未排序。使用 LINQ 执行此操作的最简单方法是什么?
//should be ordered in: first, a,b,u,z:
List<string> l = {"z","u","first","b","a"};
LINQ 中没有 prepend 方法之类的,是吗?
最佳答案
l = l.OrderBy(i => i != "first").ThenBy(i => i).ToList();
这里的技巧是根据所讨论的商品是否是您的特殊商品来排序,然后像往常一样根据您的商品排序。
既然你说你想要排序列表(使用 linq),请不要忘记将查询结果分配回列表。
你还问了一个前置方法,这个怎么样:
l = new[] { "first" }.Concat(l).ToList();
您可以轻松地将其作为扩展方法:
public static class LinqExtensions
{
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> query, T item)
{
return new[] { item }.Concat(query);
}
}
称为:
l = l.Prepend("first").ToList();
关于c# - 使用 LINQ 对列表进行排序,除了一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16277707/