如何使嵌套List成为List

时间:2017-02-03 07:04:53

标签: c# .net linq

我想要一个这样的嵌套列表:

{{"a","b","c","d"}, {"e","f"}, {"g"}}

从此列表中:

{"a","b","c","d","*","e","f","*","g"}

“*”是用于拆分列表的分隔符。

我相信有一种优雅的LINQ方式可以做到这一点,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

这是一种使用优雅的foreach-loop

的方法
List<string> input = new List<string>(){"a","b","c","d","*","e","f","*","g"};
List<List<string>> result = new List<List<string>>();
List<string> temp = new List<string>();
foreach (string item in input)
{
    if (item == "*")
    {
        result.Add(temp);
        temp = new List<string>();
    }
    else
    {
        temp.Add(item);
    }
}
result.Add(temp);

答案 1 :(得分:1)

好消息。你甚至不需要LINQ:

var list = new List<string>() { "a", "b", "c", "d", "*", "e", "f", "*", "g" };
var newList = String.Concat(list).Split('*').ToList();

(我想,除非你算上ToList。)

答案 2 :(得分:1)

如果您正在寻找 Linq ,可以试试GroupBy

  List<string> source = new List<string>() { 
    "a", "b", "c", "d", "*", "e", "f", "*", "g" };

  int index = 0;

  List<List<string>> result = source
    .Select(item => new {
       item = item,
       index = item == "*" ? ++index : index })
    .Where(chunk => chunk.item != "*")
    .GroupBy(chunk => chunk.index, 
             chunk => chunk.item)
    .Select(chunk => chunk.ToList())
    .ToList();

测试:

  string test = "{" + string.Join(", ", result
    .Select(line => "{" + string.Join(", ", line) + "}")) + "}" ;

  Console.Write(test);

结果:

  {{a, b, c, d}, {e, f}, {g}}

另一种选择,没有 Linq ,但是简单的循环方法:

  List<List<string>> result = new List<List<string>> {
    new List<string>(),
  };

  foreach (var item in source)
    if (item == "*")
      result.Add(new List<string>());
    else
      result[result.Count - 1].Add(item);