LINQ Group by 未按预期返回结果

Cen*_*rze -1 c# linq group-by

我有一个动物课:

public class Animals
{
    public string Type { get; set; }
    public string Gender { get; set; }
    public int Amount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以及与不同动物相关的成本的类别成本:

public class Cost 
{
    public string AnimalType { get; set; }
    public int Cost { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个不同类别的列表:

List<Animals> animalList = new List<Animals>()
{
     new Animals() { Type = "Wolf", Gender = "Female", Amount = 10 },
     new Animals() { Type = "Wolf", Gender = "Male", Amount = 20 },
     new Animals() { Type = "Lion", Gender = "Female", Amount = 10 }, 
     new Animals() { Type = "Horse", Gender = "Male", Amount = 5 }
};

List<Cost> cost = new List<Cost>() 
{
    new Cost() { AnimalType = "Wolf", Cost = 1000 },
    new Cost() { AnimalType = "Lion", Cost = 2000 }, 
    new Cost() { AnimalType = "Horse", Cost = 1500 }
}
Run Code Online (Sandbox Code Playgroud)

我想总结每只动物的成本,结果如​​下:

动物类型 成本
30000
狮子 20000
7500

我尝试过使用 LINQ 和 sum,如下所示:

var totalCost = from animal in animalList 
      join cost in costList 
      on animal.Type equals cost.AnimalType 
      group animal by animal.Type into g
      select g;
Run Code Online (Sandbox Code Playgroud)

但这只会返回 Wolf (据说是因为它是唯一有两种性别的),但我不明白为什么。我怎样才能写出select找到我要找的东西?

Yon*_*hun 5

问题是您当前的 LINQ 查询返回数据animal( g)。

相反,在分组时,应该构建一个包含animalcost数据的新数据集,以便您可以在投影中执行计算。

List<CostModel> costList = new List<CostModel>() 
{
    new CostModel() { AnimalType = "Wolf", Cost = 1000 },
    new CostModel() { AnimalType = "Lion", Cost = 2000 }, 
    new CostModel() { AnimalType = "Horse", Cost = 1500 }
};

var totalCost = (from animal in animalList 
           join cost in costList 
           on animal.Type equals cost.AnimalType 
           group new { Animal = animal, Cost = cost } by animal.Type into g
           select new 
            {
                AnimalType = g.Key,
                Cost = g.Sum(x => x.Cost.Cost * x.Animal.Amount)
            }).ToList();
Run Code Online (Sandbox Code Playgroud)
public class CostModel 
{
    public string AnimalType { get; set; }
    public int Cost { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

虽然您的代码中几乎没有错误:

  1. 在LINQ查询中,join cost in costList但是没有声明变量costList

  2. 您将在类中收到错误Cost,因为存在Cost与类名冲突的属性。