【C#】Linqメソッド 合計を求める/集計する ~SUM編 ~

合計を求める

 * Sum()を使用する

構文

var totalStock = productDetails.Sum(x => x.Stock);

サンプル

入れ子になった数量の合計を求める

public partial class Form1 : Form
{
    IList<Product> products;

    public Form1()
    {
        InitializeComponent();

        this.products = new List<Product>()
            {
                new Product() 
                {
                    Id = "001",
                    Name = "Book1",
                    ProductDetails = new List<ProductDetail>()
                    {
                       new ProductDetail()
                       {
                           ShopId = "X01",
                           Price = 1000,
                           Stock = 12,
                       },
                       new ProductDetail()
                       {
                           ShopId = "X02",
                           Price = 1200,
                           Stock = 5,
                       },
                       new ProductDetail()
                       {
                           ShopId = "X03",
                           Price = 2000,
                           Stock = 3,
                       },
                    },
                },
                new Product() 
                {
                    Id = "002",
                    Name = "Book2",
                    ProductDetails = new List<ProductDetail>()
                    {
                       new ProductDetail()
                       {
                           ShopId = "X01",
                           Price = 800,
                           Stock = 6,
                       },
                       new ProductDetail()
                       {
                           ShopId = "X02",
                           Price = 2500,
                           Stock = 15,
                       },
                    },
                },
            };
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var result1 = this.products.Sum(x => x.ProductDetails.Sum(y => y.Price));
        var result2 = this.products.Sum(x => x.ProductDetails.Sum(y => y.Stock));

        this.label1.Text = 
            "値段合計 : " + result1 + 
            ", 総量 : " + result2;
    }
}

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    // ★入れ子になっている★
    public IList<ProductDetail> ProductDetails { get; set; }
}
public class ProductDetail
{
    public string ShopId { get; set; }
    public decimal Price { get; set; }
    public int Stock { get; set; }
}