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

时间:2018-07-28 23:05:32

标签: 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

我该如何实现?

2 个答案:

答案 0 :(得分:2)

List<ProductionClass> orderedProduction = Production
  .OrderBy(saClass => saClass.Value1 + saClass.Value2 + saClass.Value3 + saClass.Value4)
  .ToList();

Sum方法用于对IEnumerable求和。要从您的类中获取属性总和,只需将值与+相加即可。

答案 1 :(得分:1)

好吧,艾米(Amy)首先到达那里:)

我只想补充一点,我会添加一个扩展来提供总和,然后您可以将更简单的代码重新用于后续排序。

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();
    }

}