You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用LINQ按hdr开头字符串对字符串列表进行分组?

正确的LINQ分组实现方案

你需要的是将列表按每个以"hdr"开头的元素作为分组起始,后续非"hdr"开头的元素归入前一个hdr分组,而非简单按是否为hdr元素分组。下面是两种可行的LINQ实现方式:

方式一:使用Aggregate手动构建分组

var result = test.Aggregate(new List<List<string>>(), (groups, item) =>
{
    if (item.StartsWith("hdr"))
    {
        groups.Add(new List<string> { item });
    }
    else if (groups.Count > 0)
    {
        groups.Last().Add(item);
    }
    return groups;
});

方式二:借助Scan(需引入MoreLINQ库)

如果允许使用第三方库MoreLINQ,Scan操作能更简洁地生成分组键:

// 先安装MoreLINQ:Install-Package MoreLINQ
var groupedWithKeys = test.Scan((currentGroupKey, item) => 
    item.StartsWith("hdr") ? item : currentGroupKey, 
    string.Empty);

var result = test.Zip(groupedWithKeys, (item, key) => new { item, key })
                 .GroupBy(x => x.key)
                 .Where(g => !string.IsNullOrEmpty(g.Key))
                 .Select(g => g.Select(x => x.item).ToList())
                 .ToList();

原理说明

  • 方式一通过Aggregate累积分组列表:每遇到hdr元素就新建分组,非hdr元素则添加到最后一个分组中,直接构建出目标结构。
  • 方式二先用Scan为每个元素标记所属的hdr分组键,再通过Zip将元素和键配对,最后按键分组得到结果。

内容的提问来源于stack exchange,提问作者oden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:03:33