我想要一个方法,它可以按照谓词将一个IEnumerable拆分,并根据它们相对于谓词的索引将项分组在一起。例如,它可以将一个List根据满足x => MyRegex.Match(x).Success的项拆分,这些项之间被分组在一起。
其签名可能看起来像:
其签名可能看起来像:
public static IEnumerable<IEnumerable<TSource>> Split<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate,
int bool count
)
可能还有一个输出元素包含所有分隔符的额外元素。
是否有比使用 foreach
循环更高效、更紧凑的实现方式?我感觉应该可以使用 LINQ 方法实现,但我无法确定。
示例:
string[] arr = {"One", "Two", "Three", "Nine", "Four", "Seven", "Five"};
arr.Split(x => x.EndsWith("e"));
以下任一种方式都可以:
IEnumerable<string> {{}, {"Two"}, {}, {"Four", "Seven"}, {}}
IEnumerable<string> {{"Two"}, {"Four", "Seven"}}
可选的元素用于存储匹配项,将是{"One", "Three", "Nine", "Five"}
。
Skip()
和Take()
这样的东西吗? - Frédéric Hamidi