使用LINQ </string>将List <string>拆分为基于字符串长度的子列表

时间:2013-04-29 20:46:29

标签: c# linq list sublist

非常自我解释......

此:

{"hello","this","is","an","example","string"}

会回来:

{
    {"is","an"},
    {"this"},
    {"hello"},
    {"string"},
    {"example"}
}

3 个答案:

答案 0 :(得分:7)

您可以使用GroupBy

var groups = theList.GroupBy(i => i.Length);

答案 1 :(得分:2)

List<string> list = new List<string>() { "hello", "this", "is", "an", "example", "string" };
var listOfLists = list.GroupBy(s => s.Length)
                      .OrderBy(g => g.Key)
                      .Select(g => g.ToList())
                      .ToList();

答案 2 :(得分:1)

GroupBy字符串的长度:

var result = list.GroupBy(s => s.Length).Select(g => g.ToArray());

这将导致IEnumerable<string[]>,其中每个字符串数组包含长度相同的字符串。品尝季节。