简体   繁体   English

排序列表数组 <string> 使用LINQ

[英]Sorting an array of List<string> using linq

How do I sort an array of List<string> by length of string using Linq? 如何使用Linq按字符串长度对List<string>数组进行排序? The efficiency of execution does not matter. 执行效率无关紧要。

List<string>[] col = new List<string>[]
{
    new List<string>(){"aaa", "bbb"},
    new List<string>(){"a", "b", "d"},
    new List<string>(){"xy","sl","yy","aq"}
}; //Each string in a list of strings of a particular array element has equal length.

After sorting should produce 分选后应产生

{"a", "b", "d"}, {"xy","sl","yy","aq"}, {"aaa", "bbb"} {“ a”,“ b”,“ d”},{“ xy”,“ sl”,“ yy”,“ aq”},{“ aaa”,“ bbb”}

This should work: 这应该工作:

var ordered = col.OrderBy(x => x[0].Length).ToList();

Try it out here . 在这里尝试。

If you want to sort out existing col list (ie in place sorting): 如果要整理现有的 col列表(即就地排序):

col.Sort((left, right) = > left[0].Length.CompareTo(right[0].Length));

It's not Linq , however. 但是,这不是Linq

Order by the length of the first item in each member list: 按每个成员列表中第一项的长度排序:

var ordered = col.OrderBy(c => c.First().Length);

Fiddle 小提琴


Or if it should be able to handle empty lists and nulls: 或者,如果它应该能够处理空列表和空值:

var ordered = col.OrderBy(c => c.FirstOrDefault()?.Length);

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM