Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search list of objects for maximum value by date

Tags:

c#

foreach

linq

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

Basically I have a list(ItemList) made up of ItemRows as follows

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

Currently i am in a foreach loop which passes the current variables to another function in each iteration. However when I pass the price I only ever want to pass the highest price per 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

here is how I want the loop to pass the info 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 assistance on how to select the dollar amount from my list that the foreach loop is using but I only want it to ever select the highest amount by date from said list per iteration.

I hope this makes sense and I thank you for your assistance!!

like image 953
Gazrok Avatar asked Dec 25 '22 11:12

Gazrok


1 Answers

You might want to group by the ItemDate property and handle this a bit differently. E.g.

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

This would give you a structure where each element has a Date, MaxPrice for that date and the items belonging to that date. With some small modifications in the looping you can fit this into your current structure.

Edit: as noted in another answer, you might have to convert the price to some number format if it's in string or same thing with the date property. I'd suggest do the conversion of string to date and number before getting into this logic.

like image 87
AD.Net Avatar answered Dec 27 '22 19:12

AD.Net