如何对数组 List<class> 中的条件求和?统一 C#

How to sum condition in array List<class> ? Unity C#

如何用 class 对数组列表中的条件求和?

例如:

我有这个 class :

productMerchant.cs

using UnityEngine;
using System.Collections;

public class productMerchant {
    public int productID;
    public string productName;
    public int qty;
    public int price;
    public int have;

    public productMerchant (int productid, string productname, int qtyx, int pricex, int havex) {
        this.productID = productid;
        this.productName = productname;
        this.qty = qtyx;
        this.price = pricex;
        this.have = havex;
    }
}

我有这个:

public List<productMerchant> productMargaretSell = new List<productMerchant> ();

那么如何对条件求和,例如 sum < productMargaretSell.qty > which < productMargaretSell.productID = 10 >。

如果有 3 个 producID = 10,数量 = 2, 3, 1

因此在数组中所有 productID = 10 数量将求和。结果必须是:

产品 ID = 10(数量 = 6)

没有使用 Looping 来检查 productID 是否相同然后求和。

因为如果数据太多,使用循环会导致延迟。

也许 unity c# 中内置了一些函数可以做到吗?

像这样productMargaretSell.Sum() ?

谢谢

关键词是GroupBy

public class productMerchant
    {
        public int productID { get; set; }
        public string productName { get; set; }
        public int qty { get; set; }
        public int price { get; set; }
        public int have { get; set; }

        public productMerchant(int productid, string productname, int qtyx, int pricex, int havex)
        {
            this.productID = productid;
            this.productName = productname;
            this.qty = qtyx;
            this.price = pricex;
            this.have = havex;
        }
    }

    public static void Main(string[] args)
    {
        List<productMerchant> productMerchants = new List<productMerchant>();
        productMerchants.Add(new productMerchant(10, "A", 1, 0, 0));
        productMerchants.Add(new productMerchant(10, "A", 2, 0, 0));
        productMerchants.Add(new productMerchant(10, "A", 3, 0, 0));

        productMerchants.Add(new productMerchant(11, "B", 4, 0, 0));
        productMerchants.Add(new productMerchant(11, "B", 5, 0, 0));
        productMerchants.Add(new productMerchant(11, "B", 6, 0, 0));

        //foreach (var productMerchant in productMerchants)
        //    Console.WriteLine(productMerchant.productName + " - " + productMerchant.productID + " - " + productMerchant.qty);

        var results = productMerchants.GroupBy(g => g.productID)
            .Select(x => new
            {
                id = x.Key,
                sum = x.Sum(s => s.qty)
            });

        foreach (var result in results)
            Console.WriteLine(result.id + " - " + result.sum);

    }

这可以使用 linq 轻松完成。

List<productMerchant> result = productMargaretSell
    .GroupBy(l => l.productID)
    .Select(cl => new productMerchant
            {
                productID = cl.First().productID,
                productName= cl.First().productName,
                qty= cl.Sum(c => c.qty).ToString(),
            }).ToList();