gpt4 book ai didi

c# - 将列表分解为一组索引列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:24 24 4
gpt4 key购买 nike

我有一个这样的类的实例列表。

public class Customer
{
public Guid Id { get; set; }
public Guid StoreId { get; set; }
public string Name { get; set; }
}

我需要按商店将其分解,以便我有一组列表,其中每个列表包含属于同一商店的所有客户。我试过了 grouping但这只会产生一个列表列表。我试过字典,但那给了我 Dictionary<Guid, Customer> ,当我需要类似 Dictionary<Guid, List<Customer>> 的东西时.我试着看 ILookup甚至是一个叫做 SortedDictionary 的东西.

最后我感到困惑和虚弱。

我希望能够执行这样的迭代。

foreach(KeyValuePair storeWithCustomers in brokenUpList)
{
DoSomething(storeWithCustomers.Key);
foreach(Customer customer in storeWithCustomers)
DoSomething(customer.Name);
}

它不一定是 KeyValuePair ,当然,列表的分解不一定是 ToDictionary (虽然它可能,如果它是一个好的解决方案)。

最佳答案

很简单,你只需要这样.GroupBy:

foreach(var group in customers.GroupBy(x=>x.StoreId))
{
DoSomething(group.Key);
foreach(var customer in group)
DoSomething(customer.Name);
}

关于c# - 将列表分解为一组索引列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954533/

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