简体   繁体   中英

How to find Maximum Value of Multiple Properties

We have the following Product Class.

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

The Properties hold the sales values for that day of the week. We need to be able to search a list of Products, and select the Total Sales for ALL products based on the Product's best sales day. For instance: In the sample below, product 1 has the highest sales on Monday and Product2 has the highest sales on Sunday, so the total should combine the 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

Here is the LINQ code I have so far.

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

Make an array from the sales values and get the maximum for that product:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM