按属性分组列表

问题描述 投票:0回答:1

我有

List
的购买,看起来像这样:

List<MyItem> l = new List<MyItem>();
l.Add(new MyItem(){person_id = 1, person_name = "Jim", shirt = "green", cost = 10});
l.Add(new MyItem(){person_id = 1, person_name = "Jim", shirt = "yellow", cost = 20});
l.Add(new MyItem(){person_id = 1, person_name = "Jim", shirt = "blue", cost = 30});
l.Add(new MyItem(){person_id = 2, person_name = "John", shirt = "red", cost = 40});
l.Add(new MyItem(){person_id = 2, person_name = "John", shirt = "orange", cost = 50});
l.Add(new MyItem(){person_id = 3, person_name = "Joe", shirt = "purple", cost = 60});

我希望能够按人对列表中购买的衬衫进行分组,以便我可以循环并显示每个人购买的商品,例如:

foreach(person in people)
{
    Display(p.person_id);
    Display(p.person_name);
    
    foreach(purchase in p.purchases)
    {
            Display(purchase.shirt);
            Display(purchase.cost);
    }
}

我怀疑 LINQ 有一个适合我的组选项,但我不确定它会是什么样子。

谢谢!

c# linq grouping
1个回答
0
投票

Linq 的

GroupBy()
函数采用
KeySelector
,通常这只是
Enumerable<T>
T 类型的属性,但是您可以在此处使用匿名类型并按多个属性进行分组,在本例中是人员的 Id 和 Name。 例如

var groupedList = l.GroupBy(x => new { x.person_id, x.person_name });

然后您可以通过分组进行枚举,其中

Key
包含人员的 ID 和姓名。

部分解决方案:

public static void Main()
    {
        List<MyItem> l = new List<MyItem>();
        l.Add(new MyItem(){person_id = 1, person_name = "Jim", shirt = "green", cost = 10});
        l.Add(new MyItem(){person_id = 1, person_name = "Jim", shirt = "yellow", cost = 20});
        l.Add(new MyItem(){person_id = 1, person_name = "Jim", shirt = "blue", cost = 30});
        l.Add(new MyItem(){person_id = 2, person_name = "John", shirt = "red", cost = 40});
        l.Add(new MyItem(){person_id = 2, person_name = "John", shirt = "orange", cost = 50});
        l.Add(new MyItem(){person_id = 3, person_name = "Joe", shirt = "purple", cost = 60});
        
        var groupedList = l.GroupBy(x => new { x.person_id, x.person_name });
        foreach(var groupedItem in groupedList)
        {
            Display(groupedItem.Key.person_id);
            Display(groupedItem.Key.person_name);
            
            foreach(var item in groupedItem)
            {
                Display(item.shirt);
                Display(item.cost);
            }
        }
    }

netFiddle:https://dotnetfiddle.net/bHc7In

© www.soinside.com 2019 - 2024. All rights reserved.