根据属性和重复项的总和列出不同的条目 [英] List Distinct entries based on property and sum of duplicates

查看:53
本文介绍了根据属性和重复项的总和列出不同的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我可能会问一个简单的问题,但试图获得一个优雅的解决方案.我遇到的情况是下面的行

Im wondering I may be asking a simple question, but trying to get a elegant solution. I have a situation where below are the rows

状态 标签

  1. 阿拉巴马州 AB 9
  2. 阿拉巴马州 AB 4
  3. 亚利桑那州 AZ 5
  4. 德克萨斯州 TX 6
  5. 德克萨斯州 TX 15
  6. 加利福尼亚 CA 14
  7. 加利福尼亚 CA 11
  8. 加利福尼亚 CA 2
  1. Alabama AB 9
  2. Alabama AB 4
  3. Arizona AZ 5
  4. Texas TX 6
  5. Texas TX 15
  6. California CA 14
  7. California CA 11
  8. California CA 2

考虑到上面的List<ValueLabels>对象(每个ValueLabel对象将具有状态,标签和值的集合),我应该生成另一个包含以下信息的列表.

Considering the above List<ValueLabels> object (each ValueLabel object will have set of State, Label and value), I should generate another list which contains below information.

  1. 阿拉巴马州 AB 13
  2. 亚利桑那州 AZ 5
  3. 德克萨斯州 TX 21
  4. 加利福尼亚 CA 27
  1. Alabama AB 13
  2. Arizona AZ 5
  3. Texas TX 21
  4. California CA 27

这意味着,最终,我应该获得基于State属性的唯一记录,而value属性应该是基于State属性的所有重复项的总和.

That mean, eventually, I should get a unique records based on State property and value property should be sum of all duplicate entries based on State property.

我在lambda表达式中使用了ListObj.DistinctBy(p => p.State).ToList()函数,但是无法将这些值添加到gether中.

I have used ListObj.DistinctBy(p => p.State).ToList() function with lambda expression but I could not add the values to gether.

有人可以帮助我实现上述目标吗?请让我知道是否需要更多信息.

Can anyone help me in achieving the above? Please let me know if further information is needed.

推荐答案

未经测试,但这应该可以工作.

Not tested, but this should work.

var newList = list.GroupBy(x=> new {x.State , x.Label })
                  .Select(x=> new YourClass(x.Key.State, x.Key.Label, x.Sum(x=>x.Value) ))
                  .ToList();

这篇关于根据属性和重复项的总和列出不同的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆