如何在数组列表中求和条件<类> ?团结 C#

本文关键字:团结 条件 求和 数组 列表 | 更新日期: 2023-09-27 17:57:06

如何将数组列表中的条件与类求和?

例如:

我有这个类:

产品商家.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> ();

那么如何求和条件,例如<产品玛格丽特销售.qty>哪个<产品玛格丽特销售.productID>例如。

如果有 3 个产品 ID = 10,数量 = 2, 3, 1

所以在数组中所有产品 ID = 10 数量总和。结果必须是:

产品 ID = 10(数量 = 6)

不使用循环检查产品 ID 是否相同,然后将其求和。

因为如果数据太多,使用循环会使它滞后。

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

喜欢这个产品玛格丽特卖.总和 () ?

谢谢

如何在数组列表中求和条件<类> ?团结 C#

可以通过 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();

关键字是 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);
    }