c# - 使用 Linq 根据每个项目中的值的总和对列表进行排序

标签 c# linq

我有另一个 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/

相关文章:

c# - 使用 Entity Framework 将字符串转换为 DateTime

c# - 我们如何在 C# 中以编程方式添加对目录的写访问权限?

c# - javascript:history.back() 在机器上触发回发,但在预编译时不会触发

c# - 为什么 Xunit CollectionDefinition 不能与 .NET 6 Web 应用程序中的类库一起使用?

c# - 字互操作 C# : Insert new page using existing page

c# - 具有多个 Contains/Any 的 Linq

c# - 菜鸟事: How to collect data from multiple tables most deftly?

c# - 如何在vs2012中添加对程序集的引用

.net - 构建 'flat'而不是 'tree' LINQ表达式

c# - 不确定如何在集合上运行Where来返回集合