c# - 按值(value)分组收藏

标签 c# linq

我有这两个类:

class ZoneInformation : Scores
{
    public string Zone {get;set;}
}

class Scores
{
    public string TypeQ {get;set;}
    public int High {get;set;}
    public int Low {get;set;}
}

我制作了一个这样的集合:区域和每个区域中的 3 种不同类型:

Collection<ZoneInformation> Values = new Collection<ZoneInformation>();

Values.Add(new ZoneInformation{TypeQ="Type1", Zone="Zone1", High=5, Low=6});
Values.Add(new ZoneInformation{TypeQ="Type2", Zone="Zone1", High=7, Low=8});
Values.Add(new ZoneInformation{TypeQ="Type3", Zone="Zone1", High=9, Low=10});

Values.Add(new ZoneInformation{TypeQ="Type1", Zone="Zone2", High=11, Low=12});
Values.Add(new ZoneInformation{TypeQ="Type2", Zone="Zone2", High=13, Low=14});
Values.Add(new ZoneInformation{TypeQ="Type3", Zone="Zone2", High=15, Low=16});

如何按所有区域“分组”我的“值”集合中的元素?像这样

new Scores{TypeQ="Type1", High=16, Low=18});

可以看到High=5+11,两个'Type1'之和

最佳答案

这对于 Linq 来说非常简单:

var groups = Values.GroupBy(zi => zi.TypeQ)
                   .Select(g => new Scores
                         {
                         TypeQ = g.Key, 
                         High  = g.Sum(zi=> zi.High), 
                         Low   = g.Sum(zi=> zi.Low)
                         }
              );

关于c# - 按值(value)分组收藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435477/

相关文章:

c# - 序列化类型对象时检测到循环引用...如何解决?

c# - 如何限制在C# Selenium 中运行的线程

c# - 统一2D : animator single frame animations - instant transition

c# - 无法在c#中打开链接

c# - 双重使用 C# 迭代器工作意外

asp.net-mvc - 如何根据用户在 ASP.NET MVC 中的选择对列表进行排序?

c# - 如何在返回的 LINQ 中从 db 表中排除两列?

c# - 任务取消异常 (ThrowForNonSuccess)

C# 将数组的元素移动到特定点,并将特定元素拉到前面

c# - 如何使用括号动态创建 "System.Linq.Expression"表达式