在将“人类可读”数据解析为一些更方便的数据结构时,我遇到的一个普遍问题如下:
假设我有一个兄弟元素列表:
var input = new[] {"moo", "*", "foo", "bar", "baz", "*", "roo",
"moo", "*", "*", "hoot", "*", "boot"};
我知道这*
是一个分隔符,它将所有相邻元素分组,直到下一个分隔符。所以与这个输入相关的“更方便”的数据结构是:
var expectedOutput = new List<List<string>>
{
new List<string> {"moo"},
new List<string> {"*", "foo", "bar", "baz"},
new List<string> {"*", "roo", "moo"},
new List<string> {"*"},
new List<string> {"*", "hoot"},
new List<string> {"*", "boot"}
};
过去,我将解析器编写为扩展方法,其语法与 LINQ 类似:
public static IEnumerable<IEnumerable<T>> GroupByDelimiter<T>(this IEnumerable<T> input, T delimiter)
{
var currentList = new List<T>();
foreach (T item in input)
{
if (!item.Equals(delimiter))
{
currentList.Add(item);
}
else
{
yield return currentList;
currentList = new List<T> {item};
}
}
// return the last list
yield return currentList;
}
这很好用,但我想知道是否可以使用现有的 LINQ 扩展方法重写此GroupByDelimiter
方法。更好的是,是否有一些我不知道的 LINQ 方法已经这样做了?