如何查找多个属性的最大值

时间:2013-08-20 22:55:49

标签: c# linq

我们有以下产品类别。

public string Product{ get; set; }       
public int? Monday { get; set; }
public int? Tuesday { get; set; }
public int? Wednesday { get; set; }
public int? Thursday { get; set; }
public int? Friday { get; set; }
public int? Saturday { get; set; }
public int? Sunday { get; set; }
public string Zip { get; set; }  

属性包含一周中该日的销售值。我们需要能够搜索产品列表,并根据产品的最佳销售日选择所有产品的总销售额。例如:在下面的示例中,产品1在星期一销售额最高,而Product2在星期日销售额最高,因此总计应合并2(5378)。

 Product    Zip     City        State   Sunday  Monday  Tuesday Wednesday Thursday Friday

 Product 1  63103   Saint Louis MO      0       4728    0       1522      0        0

 Product 2  63103   Saint Louis MO      650     419     417     428       599      559

这是我到目前为止的LINQ代码。

 var temp = report.SelectMany(p => p.SnapshotRecords)
                                 .Where(record => record.Zip == "63103")
                                 .GroupBy(g => new
                                     {
                                         g.Zip,
                                         g.ProductID
                                     })
                                 .Select(s => new SnapshotData()
                                     {
                                         Monday = s.Sum(g => g.Monday),
                                         Tuesday = s.Sum(g => g.Tuesday),
                                         Wednesday = s.Sum(g => g.Wednesday),
                                         Thursday = s.Sum(g => g.Thursday),
                                         Friday = s.Sum(g => g.Friday),
                                         Saturday = s.Sum(g => g.Saturday),
                                         Sunday = s.Sum(g => g.Sunday),
                                     });

1 个答案:

答案 0 :(得分:2)

根据销售值创建一个数组并获得该产品的最大值:

int? total = report.SelectMany(p => p.SnapshotRecords)
  .Where(record => record.Zip == "63103")
  .GroupBy(g => new
    {
      g.Zip,
      g.ProductID
    })
  .Sum(s => new int?[]
    {
      s.Sum(g => g.Monday),
      s.Sum(g => g.Tuesday),
      s.Sum(g => g.Wednesday),
      s.Sum(g => g.Thursday),
      s.Sum(g => g.Friday),
      s.Sum(g => g.Saturday),
      s.Sum(g => g.Sunday)
    }.Max()
  );