如何使用LINQ合并树

如何使用LINQ合并树

本文介绍了如何使用LINQ合并树(和总数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这些课程:

public class Option
{
    public int OptionID { get; set; }
    public bool IsSelected { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    public int Quantity { get; set; }
    public List<Option> Options { get; set; }
}

假设这是将一些Product对象添加到List<Product>

Let's say this would be my result after adding some Product objects into a List<Product>

2x Product 1 OptionID 1 OptionID 1 OptionID 2 OptionID 2

2x Product 1 OptionID 1 OptionID 1 OptionID 2 OptionID 2

2x Product 1 OptionID 1 OptionID 1 OptionID 2 OptionID 2

2x Product 1 OptionID 1 OptionID 1 OptionID 2 OptionID 2

如何使用LINQ(lambda)将这些结果转换为单个结果,其中IsSelected = true?

How can I convert these results into a single result using LINQ (lambda), where IsSelected = true?

4x Product 1 4x OptionID 1 4x OptionID 2

4x Product 1 4x OptionID 1 4x OptionID 2

推荐答案

虽然Konrad的答案很接近,但并不能完全满足您的需求.它需要使用匿名类型和两个组.

While Konrad's answers is close, it doesn't quite provide what you're wanting. It needs to use anonymous types and two groups.

这是一个小提琴: https://dotnetfiddle.net/v907me 及其最相关的代码.

Here's a fiddle: https://dotnetfiddle.net/v907me and its most relevant code.

var query = products.GroupBy(p => p.ProductID, (key, values) => new
{
    ProductID = key,
    Quantity = values.Sum(v => v.Quantity),
    Options = values
        .SelectMany(v => v.Options.Where(o => o.IsSelected))
        .GroupBy(o => o.OptionID, (k, v) => new
        {
            OptionID = k,
            Quantity = v.Count()
        })
});

这篇关于如何使用LINQ合并树(和总数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:33