简体   繁体   English

如何使用LINQ获取所有不同值的总和

[英]How to get Sum of all distinct values using LINQ

I have ComboUniqueId and this basis I want ComboAmount, my problem is how to get distinct ComboAmount on ComboUniqueId basis please help me this, my code is below: 我有ComboUniqueId ,在此基础上,我想要ComboAmount,我的问题是如何在ComboUniqueId基础上获取不同的ComboAmount ,请帮帮我,我的代码如下:

ComboUniqueId it is string ComboUniqueId它是字符串

decimal FinalTotal = 0;

var ListUnique = this.OrderDetailArr.Select(x => new {
    ComboAmount = x.ComboAmount,
    ComboId = x.ComboId,
    ComboUniqueId = x.ComboUniqueId,
    ItemAddOnsArr = x.ItemAddOnsArr,
    TotalPrice =  x.TotalPrice
}).Distinct(x=> x.ComboUniqueId);

for (int i = 0; i < ListUnique.Length; i++)
{
    FinalTotal += ListUnique[i].TotalPrice;
    if(ListUnique[i].ComboId != null)
    {
        FinalTotal = ListUnique[i].ComboAmount;
    }
    if (ListUnique[i].ItemAddOnsArr != null)
    {
        for (int g = 0; g < this.OrderDetailArr[i].ItemAddOnsArr.Length; g++)
        {
            FinalTotal += this.OrderDetailArr[i].ItemAddOnsArr[g].AddOnTotalPrice;
        }
    }
}

Sounds like this.OrderDetailArr has duplicates and you want them removing. 听起来像这样this.OrderDetailArr有重复项,您希望将其删除。

You can do this with code similar to the following, instead of creating an anonymous object: 您可以使用类似于以下代码的方式来执行此操作,而不是创建一个匿名对象:

var ListUnique = this.OrderDetailArr
    // Group on the ComboUniqueId, you'll get 1 key with multiple values for duplicates
    .GroupBy(m => m.ComboUniqueId)
    // By retrieving the First(), you're limiting your result set to 1 per the group
    .Select(m => m.First());

The remainder of your code should work in place. 您代码的其余部分应该可以使用。

There's no need to create a new anonymous type here ( .Select(.. => new {..}) ) because you're only pulling properties from the source anyway, so you might as well keep it. 无需在此处创建新的匿名类型( .Select(.. => new {..}) ),因为无论如何您只是从源中提取属性,因此最好保留它。

If you're set on using Distinct , you'd need an EqualityComparer<T> for your object type, that only looks at the ComboUniqueId property of the object to compare equality, you could then use that in a Distinct method as per your original code. 如果您设置使用Distinct ,则需要为对象类型使用EqualityComparer<T> ,该对象仅查看对象的ComboUniqueId属性以比较相等性,然后可以按照原始方法在Distinct方法中使用它码。 Note that it again would not work with your anonymous type. 请注意,它再次不适用于您的匿名类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM