简体   繁体   English

具有相同属性值的集合中的 Select 个对象

[英]Select objects from a collection with same property values

Is there an easy way to select the members with same currencyId's so I can sum them with each other, or do I need to do else if for every currencyId there is?有没有一种简单的方法可以将具有相同 currencyId 的成员加到 select,这样我就可以将它们相互求和,或者如果每个 currencyId 都存在,我还需要做其他事情吗?

if(model.CurrencyId == -1)
        {
            resultModel.Add(new ReportModel
            {
                AccountName = "Sum",
                BalanceSum = resultModel.Where(q => q.CurrencyId == 1).Sum(q => q.Balance)

            });
        }
        else
        {
            resultModel.Add(new ReportModel
            {
                AccountName = "Sum",
                BalanceSum = resultModel.Sum(q => q.Balance)

            });
        }

To get the sum of the balance for each currency, you can preform groupBy , followed by select & sum .要获得每种货币的余额总和,您可以groupBy ,然后是select & sum

Eg:例如:

var balanceSum = t.GroupBy(q => q.CurrencyId)
    .Select(q => q.Sum(x => x.Balance));

To add it to the resultModel, you can do something like:要将其添加到 resultModel,您可以执行以下操作:

var reportData = t.GroupBy(q => q.CurrencyId)
    .Select(q => new ReportModel()
    {
        AccountName = "Sum",
        BalanceSum = q.Sum(x => x.Balance)
    });

resultModel.AddRange(reportData);

If the data is only assigned to resultModel once, then you can probably replace AddRange with equals.如果数据只分配给 resultModel 一次,那么您可以将 AddRange 替换为 equals。

暂无
暂无

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

相关问题 使用PLINQ从对象集合中选择nullable属性的nonNullable值 - Select nonNullable values of nullable property from collection of objects with PLINQ WPF绑定到集合中多个对象的相同属性 - WPF binding to the same property of multiple objects in a collection 如何根据子集合中的值 select 对象? - How to select objects based on values in sub collection? 如何 select 列表中的 5 个随机对象,但是一旦选择了 object 就排除具有相同属性值的其他对象 - How to select 5 random objects from a List, but once an object is selected exclude other objects with the same property value C#LINQ选择具有相同值的一个属性的对象连接其他值 - C# LINQ Select objects with the same value of one property join values of other 强制转换以从集合中的.Last()获取属性 - Casting a Select to get a property from .Last() in a collection LINQy检查集合中的任何对象是否具有相同属性值的方法 - LINQy way to check if any objects in a collection have the same property value 选择返回真/假值的集合,而不是匹配条件的对象列表 - Select returning a collection of true/false values, not a list of objects matching criteria 使用 Linq 查询选择属性的任何值与列表中的值匹配的对象 - Using a Linq query to select objects where any value of a property matches values from a list LINQ - 从嵌套集合中选择正确的值 - LINQ - Select correct values from nested collection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM