【问题标题】:split a List<Product> into SubLists<Product>将 List<Product> 拆分为 SubLists<Product>
【发布时间】:2012-04-24 09:16:23
【问题描述】:

我有一个包含类别和产品作为属性的列表,我希望将属于不同列表的类别的所有产品分开。

目前我有这个

Products products = new Products();

        products.productList.Add(new Products("Fruit", "Apples"));
        products.productList.Add(new Products("Fruit", "Oranges"));
        products.productList.Add(new Products("Fruit", "Bananas"));
        products.productList.Add(new Products("Fruit", "Grapes"));
        products.productList.Add(new Products("Vegetables", "Tomatoes"));
        products.productList.Add(new Products("Vegetables", "Lettuce"));
        products.productList.Add(new Products("Vegetables", "Onions"));
        products.productList.Add(new Products("Dairy", "Milk"));
        products.productList.Add(new Products("Dairy", "Yogurth"));
        products.productList.Add(new Products("Dairy", "Eggs"));

        List<IEnumerable<string>> distinctCats = products.productList.GroupBy(s => s.Category).Select(s => s.Select(v => v.Product)).ToList();

但我似乎无法从 distinctCats 中获取值。而且我想得到一个带有实际值的普通 List productList 之类的东西。

感谢您的帮助和时间

【问题讨论】:

  • 你期待什么输出?不同类别的列表,还是包含该类别产品列表的类别列表?

标签: c# linq c#-4.0 linq-to-objects


【解决方案1】:

如果要将列表按类别划分为子列表:

var categoryLists = products.GroupBy(p => p.Category)
                            .Select(g => g.ToList());

现在,categoryListsIEnumerable&lt;List&lt;Product&gt;&gt;

要迭代这个,你可以说:

foreach(var categoryList in categoryLists) {
    foreach(var product in categoryList) {
        // do something with product
    }        
}

【讨论】:

  • 嗨 Jason 是的,我想要 var categoryLists = products.GroupBy(p => p.Category) .Select(g => g.ToList());但是如何在其中进行迭代以获取类别和产品列表?
【解决方案2】:

不确定我是否理解你想要什么,但似乎你需要这样的东西:

var products=new List<Product>{};
var productsInCategories=products.ToLookup(p=>p.Category);

现在每个 productsInCategories[i] 都包含一个“subList”(实际上是 IEnumerable)。

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多