Если у вас Поиск 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);
читаемый, классный и простой; все одновременно. –
Я думаю, что ваш путь является самым читаемым во всех ответах. Легко понять, нет расчета индекса. Благодаря! – lowcac