除与LINQ一个条目排序列表 [英] Sort List except one entry with LINQ

查看:120
本文介绍了除与LINQ一个条目排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要订​​购的字符串列表,但列表中的一个字符串应该是始终在开始和排序。什么是LINQ做到这一点最简单的方法。



  //应该下令:第一,A,B,U, Z:
名单,LT;字符串> L = {Z,U,第一,B,一个};



THRE是LINQ没有前置的方法还是什么?


解决方案

  L = l.OrderBy(I =>!I =第一)ThenBy。(I = I标记)。了ToList(); 



这里的窍门是有问题的项目是否为你的特殊项目,然后为了你的订购项目像往常一样。



既然你说你想订购列表(LINQ)别忘了查询的结果分配回列表中。






您还问到一个前置的方法,这个怎么样:

  L =新的[] {第一} .Concat(L).ToList(); 

您可以轻松地让它的扩展方法:

 公共静态类LinqExtensions 
{
公共静态的IEnumerable< T>前面加上< T>(这个IEnumerable的< T>的查询,T项目)
{
返回新的[] {}项.Concat(查询);
}
}



称为:

  L = l.Prepend(第一)了ToList()。 


i want to order a List of strings but one string in the list should be always at the beginning and not sorted. What is the easiest way to do this with linq?

//should be ordered in: first, a,b,u,z:
List<string> l = {"z","u","first","b","a"};  

Thre is no prepend method or something in LINQ?

解决方案

l = l.OrderBy(i => i != "first").ThenBy(i => i).ToList();

The trick here is to order by whether the item in question is your special item, then order by your item as you normally would.

Since you said you want to order a list (with linq) don't forget to assign the result of the query back to the list.


You also asked about a prepend method, how about this:

l = new[] { "first" }.Concat(l).ToList();

You could easily make it an extension method:

public static class LinqExtensions
{
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> query, T item)
    {
        return new[] { item }.Concat(query);
    }
}

called as:

l = l.Prepend("first").ToList();

这篇关于除与LINQ一个条目排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆