我需要过滤以下列表以返回以"Group"开头的第一个项目开始的所有项目,直至,但不包括以"Group"开头的下一个项目(或直至最后一个项目).
List<string> text = new List<string>();
text.Add("Group Hear It:");
text.Add(" item: The Smiths");
text.Add(" item: Fernando Sor");
text.Add("Group See It:");
text.Add(" item: Longmire");
text.Add(" item: Ricky Gervais Show");
text.Add(" item: In Bruges");
Run Code Online (Sandbox Code Playgroud)
过滤后,我希望在第一个分组中包含以下项目:
Run Code Online (Sandbox Code Playgroud)"Group Hear It:" " item: The Smiths" " item: Fernando Sor"
以及第二组中的以下项目:
Run Code Online (Sandbox Code Playgroud)"Group See It:" " item: Longmire" " item: Ricky Gervais Show" " item: In Bruges"
这不起作用,因为我在第一个过滤列表的地方过滤了"item:"项目...我是用TakeWhile关闭还是关闭?
var group = text.Where(t => t.StartsWith("Group ")))
.TakeWhile(t => t.ToString().Trim().StartsWith("item"));
Run Code Online (Sandbox Code Playgroud)
Pat*_*sey 11
像杰夫·梅尔卡多一样,但没有预先处理整个可枚举:
public static class Extensions
{
public static IEnumerable<IList<T>> ChunkOn<T>(this IEnumerable<T> source, Func<T, bool> startChunk)
{
List<T> list = new List<T>();
foreach (var item in source)
{
if(startChunk(item) && list.Count > 0)
{
yield return list;
list = new List<T>();
}
list.Add(item);
}
if(list.Count > 0)
{
yield return list;
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用如下:
List<string> text = new List<string>();
text.Add("Group Hear It:");
text.Add(" item: The Smiths");
text.Add(" item: Fernando Sor");
text.Add("Group See It:");
text.Add(" item: Longmire");
text.Add(" item: Ricky Gervais Show");
text.Add(" item: In Bruges");
var chunks = text.ChunkOn(t => t.StartsWith("Group"));
Run Code Online (Sandbox Code Playgroud)