我有几个编号列表存储在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。
答案 0 :(得分:2)
听起来你可以使用字典类型。您可以将项目编号设置为键,将项目本身设置为值,而不是存储项目编号和项目本身。以下是如何实现这一目标的示例:
newList = {'1':'Apple','2':'Banana','3':'Pear'}
animalList = {'1':'Bear','2':'Cat','3':'Dog'}
您可以遍历每个项目,或使用方法按键或值进行调用。
答案 1 :(得分:2)
List<List<string>> result = all.GroupAdjacent((g, x) => !x.StartsWith("1."))
.Select(g => g.ToList())
.ToList();
使用here中的 GroupAdjacent扩展方法。
答案 2 :(得分:1)
获得所需结果的另一种选择(按顺序为每个项目分配组索引,然后按该索引分组):
int groupIndex = 0;
List<List<string>> split = all.Select(s => {
if (s.StartsWith("1."))
groupIndex++;
return new { groupIndex, s }; })
.GroupBy(x => x.groupIndex)
.Select(g => g.Select(x => x.s).ToList())
.ToList();
另一个选项 - 累积结果(这将需要对列表进行一次遍历)
List<List<string>> split =
all.Aggregate(new List<List<string>>(), (acc, s) =>
{
if (s.StartsWith("1."))
acc.Add(new List<string>());
acc[acc.Count - 1].Add(s);
return acc;
});
答案 3 :(得分:0)
在没有对列表做出一系列假设的情况下,使用LINQ实际上没有 slick 这样的方法,并且您给我们的唯一保证信息是“那里永远是1。“。是否总会有3个项目组,或者有时候会有更多或更少?
为什么不改变字符串的存储方式 - 改为使用List<List<string>>
,所以List
为List<string>
?