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

如何用C# LINQ按部门分组遍历列表并获取对应商品

C# LINQ按邮箱分组获取商品列表

首先确保test类的定义(匹配你提供的构造函数参数):

public class test
{
    public string Department { get; set; }
    public string Email { get; set; }
    public string Product { get; set; }

    public test(string department, string email, string product)
    {
        Department = department;
        Email = email;
        Product = product;
    }
}

分组与遍历实现

使用LINQ的GroupBy方法按邮箱地址分组,提取每个分组对应的商品列表后遍历处理:

// 你的测试列表初始化代码
List<test> test = new List<test>();
test.Add(new test("Bakery", "bakery@store.com", "Donut"));
test.Add(new test("Bakery", "bakery@store.com", "Bagel"));
test.Add(new test("Bakery", "bakery@store.com", "Cake"));
test.Add(new test("Produce", "produce@store.com", "Apple"));
test.Add(new test("Dairy", "dairy@store.com", "Milk"));
test.Add(new test("Dairy", "dairy@store.com", "Yogurt"));

// 按邮箱分组,生成包含邮箱和对应商品的集合
var groupedProducts = test.GroupBy(item => item.Email)
                          .Select(g => new
                          {
                              Email = g.Key,
                              Products = g.Select(p => p.Product).ToList()
                          });

// 遍历分组结果
foreach (var group in groupedProducts)
{
    // 按需求格式输出,也可根据实际场景处理商品集合
    Console.WriteLine($"给 {group.Email} 对应 {string.Join("、", group.Products)}");
}

输出结果

运行后会输出:

给 bakery@store.com 对应 Donut、Bagel、Cake
给 produce@store.com 对应 Apple
给 dairy@store.com 对应 Milk、Yogurt

如果后续部门和邮箱不是一一对应关系,可将分组键改为new { item.Department, item.Email },确保按部门+邮箱的组合分组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:40:32