使用Linq根据每个项目中的值的总和对列表进行排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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进行求和。要从类中获取属性的总和,只需使用+
添加值。
另一答案
嗯,艾米先到了那里:)
我只想补充一点,我会添加一个提供总和的扩展,然后你可以重用更简单的代码进行后续排序。
public static class GetSum
{
public static double SumOfValues(this ProductionClass item) =>
item.Value1 + item.Value2 + item.Value3 + item.Value4;
}
public class ProductionClass
{
public string Plant { get; set; }
public double Value1 { get; set; }
public double Value2 { get; set; }
public double Value3 { get; set; }
public double Value4 { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var 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 });
List<ProductionClass> orderedProduction = Production.OrderBy(row => row.SumOfValues()).ToList<ProductionClass>();
foreach(ProductionClass item in orderedProduction)
Console.WriteLine($" {item.Plant} {item.SumOfValues()}");
Console.ReadKey();
}
}
以上是关于使用Linq根据每个项目中的值的总和对列表进行排序的主要内容,如果未能解决你的问题,请参考以下文章