gpt4 book ai didi

c# - 使用 C#,LINQ 如何一次又一次地在标记之间选择项目?

转载 作者:太空狗 更新时间:2023-10-29 23:57:06 25 4
gpt4 key购买 nike

假设我有一个字符串数组:

string[] strArray = {"aa", "bb", "xx", "cc", "xx", "dd", "ee", "ff", "xx","xx","gg","xx"};

如何使用 LINQ 将“xx”标记之间的字符串提取为组?

比如将它们写入控制台:

cc
dd,ee,ff
gg

最佳答案

纯功能解决方案(无突变):

string[] strArray = { "aa", "bb", "xx", "cc", "xx", "dd", 
"ee", "ff", "xx", "xx", "gg", "xx" };

var result =
strArray.Aggregate((IEnumerable<IEnumerable<string>>)new IEnumerable<string>[0],
(a, s) => s == "xx" ? a.Concat(new[] { new string[0] })
: a.Any() ? a.Except(new[] { a.Last() })
.Concat(new[] { a.Last().Concat(new[] { s }) }) : a)
.Where(l => l.Any());

// Test
foreach (var i in result)
Console.WriteLine(String.Join(",", i.ToArray()));

如果要过滤掉最后一个标记之后的结果:

string[] strArray = { "aa", "bb", "xx", "cc", "xx", "dd", 
"ee", "ff", "xx", "xx", "gg", "xx"};

var result =
strArray.Aggregate(
new { C = (IEnumerable<string>)null,
L = (IEnumerable<IEnumerable<string>>)new IEnumerable<string>[0] },
(a, s) => s == "xx" ? a.C == null
? new { C = new string[0].AsEnumerable(), a.L }
: new { C = new string[0].AsEnumerable(), L = a.L.Concat(new[] { a.C }) }
: a.C == null ? a : new { C = a.C.Concat(new[] { s }), a.L }).L
.Where(l => l.Any());

// Test
foreach (var i in result)
Console.WriteLine(String.Join(",", i.ToArray()));

关于c# - 使用 C#,LINQ 如何一次又一次地在标记之间选择项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/813560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com