如何对List< List< string>>进行排序根据List< string>字段数? [英] How to sort List<List<string>> according to List<string> number of fields?
问题描述
如何根据字段数对List< List< string >>进行排序?
How do I sort List<List<string>> according to number of fields?
列表的结构类似
a|b|c|d|eeee|rere|ewew|
ewqewq|ewew|
ewew|ewewewewew|
通过排序,我想根据块数(升序/降序)进行操作
By Sort I'd like to do it according to numbers of blockes (asc/desc)
编辑
<list<list<string>> is "items"
和我通过
这些项目[xx]是一个列表,这意味着我希望它们将数组排序为
these items[xx] is a list which means that I want them to sort the array to
a|b|c|d|eeee|rere|ewew|
a|b|c|d|eeee|rere
a|b|c|d|eeee
推荐答案
如果您不需要就地"排序,则可以使用LINQ为您提供新的排序列表.
If you don't need to sort "in place" you can use LINQ to give you a new sorted, list.
var sorted = oldList.OrderBy( l => l.Count );
否则,您将需要编写自己的比较器,该比较器接受两个列表并按其大小返回顺序.
Otherwise you'll need to write your own Comparer that takes two lists and returns the ordering by their size.
public class CountComparer : IComparer<List<string>>
{
#region IComparer<List<string>> Members
public int Compare( List<string> x, List<string> y )
{
return x.Count.CompareTo( y.Count );
}
#endregion
}
oldList.Sort( new CountComparer() );
或者,就像@Josh指出的那样,您可以使用lambda表达式来完成此操作.
Or, as @Josh points out, you can do this with a lambda expression.
oldList.Sort( (a,b) => a.Count.CompareTo( b.Count ) )
如果比较相对简单或只使用一次,IMO就可以很好地工作,但是实际类可能更可取,因为比较变得更加复杂,或者您需要在多个地方重复它.
IMO this latter works well if the comparison is relatively simple or used once, but the actual class may be preferable as the comparison gets more complex or if you need to repeat it in multiple places.
这篇关于如何对List< List< string>>进行排序根据List< string>字段数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!