我有另一个 LINQ 计算问题。
我有一个由类项目组成的列表:
List<ProductionClass> Production = new List<ProductionClass>();
Production.Add(new ProductionClass() { Plant = "Plant A", Value1 = 94.4, Value2 = 97.2, Value3 = 71.9, Value4 = 12.8 });
Production.Add(new ProductionClass() { Plant = "Plant B", Value1 = 84.1, Value2 = 95.2, Value3 = 64.8, Value4 = 92.5 });
Production.Add(new ProductionClass() { Plant = "Plant C", Value1 = 43.1, Value2 = 66.3, Value3 = 92.7, Value4 = 84.0 });
Production.Add(new ProductionClass() { Plant = "Plant D", Value1 = 72.6, Value2 = 51.2, Value3 = 87.9, Value4 = 68.1 });
我想重新排序该列表,但基于列表中每个条目的 Value1、2、3 或 Value1、2、3、4 的总和。
因此,我希望将列表保持在其当前形式,并包含所有单独的值,以便我可以遍历它,但我希望它按计算顺序排列。
形式为:
List<ProductionClass> orderedProduction = Production.OrderBy(i => i.Sum(i.Value1 + i.Value2 + i.Value3 + i.Value4)).ToList();
所以对于这个例子,这将是排序的顺序:
{ Plant = "Plant A", Value1 = 94.4, Value2 = 97.2, Value3 = 71.9, Value4 = 12.8 } // Total = 276.3
{ Plant = "Plant D", Value1 = 72.6, Value2 = 51.2, Value3 = 87.9, Value4 = 68.1 } // Total = 279.8
{ Plant = "Plant C", Value1 = 43.1, Value2 = 66.3, Value3 = 92.7, Value4 = 84.0 } // Total = 286.1
{ Plant = "Plant B", Value1 = 84.1, Value2 = 95.2, Value3 = 64.8, Value4 = 92.5 } // Total = 336.6
我怎样才能做到这一点?
最佳答案
List<ProductionClass> orderedProduction = Production
.OrderBy(saClass => saClass.Value1 + saClass.Value2 + saClass.Value3 + saClass.Value4)
.ToList();
Sum
方法用于对 IEnumerable 求和。要从您的类中获取属性的总和,只需使用 +
添加值即可。
关于c# - 使用 Linq 根据每个项目中的值的总和对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575918/