Search for a list of objects for the maximum value by date

Hopefully I can explain my situation well enough for some help.

Basically, I have a list (ItemList) consisting of ItemRows as follows

ItemRows
        public string ItemId { get; set; }
        public string ItemDate { get; set; }
        public string ItemPrice { get; set; }

I am currently in a foreach loop that passes the current variables to another function in each iteration. However, when I transfer the price, I only ever want to transfer the highest price for the ItemDate.

foreach item in ItemList
{
    AnotherFunction(ItemId, ItemDate, MaxPriceByDate);
}

So, if I had the following 4 rows of data ....

123, 01/01/2015, $15
234, 01/01/2015, $20
345, 01/02/2015, $10
456, 01/02/2015, $5

this is how I want the loop to pass information along:

first iteration:  123, 01/01/2015, $20
second iteration: 234, 01/01/2015, $20
third iteration:  345, 01/02/2015, $10
fourth iteration: 456, 01/02/2015, $10

Basically I am looking for help in how to select the dollar amount from my list that uses the foreach loop, but I want it to always select the highest amount by date from the specified list for iteration.

Hope this makes sense and I thank you for your help!

+4
4
foreach(var item in ItemList)
{
    AnotherFunction(item.ItemId, item.ItemDate, ItemList.Where(x => x.ItemDate == item.ItemDate)
                                                        .OrderByDesc(z => Convert.ToInt32(z.ItemPrice.Replace("$", "")))
                                                                                 .First().ItemPrice);
}
+3

ItemDate . .

 var grouped = (from r in rows
                 group r by r.ItemDate into g
                 select new { Date = g.Key, MaxPrice = g.Max(gg=>gg.ItemPrice)
                 Items = g})

, Date, MaxPrice , . .

: , - , date. , .

+4

, , MaxPricePerDate, linq:

int nMaxPrice = ItemList.Where(i => i.ItemDate == item.ItemDate
                        .Max(i => Convert.ToInt32(i.ItemPrice));

, $, , i.ItemPrice.Replace("$", "");

The call is Convertnecessary to convert the string to int, however it is dangerous, as if the string was not in the correct format, an exception might be thrown. Consider also the search inInt32.TryParse();

+3
source

You can use Linqto find the maximum price for current data. This is probably not the most efficient way, but it will work:

  foreach(var item in itemList)
  {
        Console.WriteLine("{0} {1} {2}", item.ItemId, item.ItemDate, itemList.Where(i => i.ItemDate == item.ItemDate).Max(d => d.ItemPrice));
  }
0
source

Source: https://habr.com/ru/post/1619923/


All Articles