1

Is it possible to use a Lambda expression to return the minimum value of one field (ProgramQuantity) in a List of a custom class and another field(Program Price) in that class? If so, what might it look like?

decimal listMinQty = 0;
     List<PriceLevel> TrackPrice = new List<PriceLevel>();

        // add data to list here ...

        listMinQty = TrackPrice.Min(c => c.ProgramQuantity);// CAN I RETURN more than ProgramQuantity?

    }
            public class PriceLevel
    {
        public decimal ProgramPrice         { get; set; }
        public int ProgramQuantity          { get; set; }
        public DateTime ProgramLastTime     { get; set; }// Last Order Time
    }
Greg
  • 85
  • 6
  • In your specific example you could order by ProgramQuantity Descending and use `.Take` to return the first 3 results. Do you need it to be more general than that?`TrackPrice.OrderByDescending(c => c.ProgramQuantity).Take(3)` – Bradley Uffner Dec 14 '15 at 18:55
  • Currently your question isn't clear. If you want the item that has the minimum `ProgramQuanity` value you need to specifically say that and then you'd need to tell us how to break potential ties if more than one item has the same minimum value for `ProgramQuantity`. – juharr Dec 14 '15 at 19:06
  • My mistake. corrected – Greg Dec 14 '15 at 19:11

1 Answers1

1

If you would like to find the item for which you get the Min, you could do it like this:

var minItem = TrackPrice.OrderBy(c => c.ProgramQuantity).First();

Now you can take minItem.ProgramQuantity and minItem.ProgramPrice.

You could also use MinBy extension to avoid sorting:

var minItem = TrackPrice.MinBy(c => c.ProgramQuantity);
var minQty = minItem.ProgramQuantity;
var priceOfMin = minItem.ProgramPrice;
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Is it possible to update the List using minItem.ProgramPrice & minItem.ProgramQuantity like:minItem.ProgramPrice = loopLastPrice; – Greg Dec 14 '15 at 19:05
  • 1
    @Greg Since `PriceLevel` is a mutable `class`, the answer is "yes". Note, however, that it would not be possible if `PriceLevel` were a `struct`. – Sergey Kalinichenko Dec 14 '15 at 19:06
  • That's what I was looking for. Thanks all – Greg Dec 14 '15 at 19:14