gpt4 book ai didi

c# - 根据编号拆分字符串列表

转载 作者:行者123 更新时间:2023-12-02 22:20:31 25 4
gpt4 key购买 nike

我有几个编号列表存储在 List<string> 中:

List<string> all = new List<string>()
{
"1. Apple",
"2. Banana",
"3. Coconut",
"1. Ant",
"2. Beaver",
"3. Cat"
...
}

我想将此列表拆分为一个列表列表,其中每个列表包含 1-3 个。

List<List<string>> split = new List<List<string>>()
{
new List<string>() { "1. Apple", "2. Banana", "3. Coconut"},
new List<string>() { "1. Ant", "2. Beaver", "3. Cat"}
}

总会有“1”。所以我可以用它作为我的分隔符。有没有一种巧妙的方法可以使用 LINQ 来执行此操作而无需两个嵌套的 for 循环?

更新:我希望将其推广到任何长度,而不是总是 3。

最佳答案

List<List<string>> result = all.GroupAdjacent((g, x) => !x.StartsWith("1."))
.Select(g => g.ToList())
.ToList();

使用来自 hereGroupAdjacent 扩展方法 .

关于c# - 根据编号拆分字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13783010/

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