具有相同名称但具有计算的一个Linq的其他列

时间:2017-12-09 14:16:34

标签: c# sql linq duplicates

我在数据库中有数据,如

1     CP     12
2     OB     8
1     CP     19
3     AB     22
2     OB     33
1     CP     19
3     AB     22

运行查询后我想要的是什么

2     OB     41
1     CP     60
3     AB     44

我尝试了什么

 var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName, x.Weight }).Select(y => new 
{
oilType = y.Key.OilTypeName,
weight = y.Sum(z => z.Weight)
});

但我失败了......给我一个类似的格式

由于

2 个答案:

答案 0 :(得分:1)

x.Weight

中删除GroupBy
var abc = db.OilVolumes.GroupBy(x => new { x.OilType.OilTypeName }).Select(y => new 
    {
     oilType = y.Key.OilTypeName,
     weight = y.Sum(z => z.Weight)
    });

答案 1 :(得分:0)

数字和名称似乎是多余的,所以我跳过了这个数字。我假设你有一个这样的课程:

public class OilVolume
{
    public int Volume { get; set; }
    public string Name { get; set; }
    public OilVolume(string name, int value)
    {
        this.Name = name;
        this.Volume = value;
    }

    public override string ToString(){
        return $"{Name} {Volume}";
    }
}

然后查询所需的输出将是:

var oilSums = db.OilVolumes
  .GroupBy(oil => oil.Name)
  .Select(group => new OilVolume(group.Key,  group.Sum(oil => oil.Volume)))
  .OrderByDescending(oil => oil.Volume);

的输出
foreach (var oil in oilSums)
 Console.WriteLine(oil);

CP 50
AB 44
OB 41

我认为你的例子中的CP 60是错误的?