问题
I have a List of Items:
List<Item> items = new List<Item>();
items.add(new Item("cow", 4));
items.add(new Item("pig", 7));
items.add(new Item("dog", 12));
I want to retreive the item with the minimum Value
(where the numbers are that Value
). How would I do that?
I am trying to avoid a nasty foreach
loop. I am looking for something along the lines of:
return items.Min(Value);
回答1:
You can get the minimum value first, then get the item that has the minimum value:
var minValue = items.Min(x => x.Value);
var item = items.First(x => x.Value == minValue);
You can also do that in one line that won't be efficient because it will perform Min
for each item:
var item = items.First(x => x.Value == items.Min(x => x.Value));
回答2:
You can order the items by the Value
, then use First
to take the lowest:
Item lowestValueItem = items
.OrderBy(i => i.Value)
.First();
Another (more efficient) way, MinBy of morelinq.
回答3:
I have a utility method to do that which is quite efficient and re-usable! It only iterates over collection once (n complexity).
public static TItem GetMinItem<TItem>(this IEnumerable<TItem> items) where TItem : IComparable<TItem>
{
TItem minItem = default(TItem);
bool isFirstItem = true;
foreach (var item in items)
{
if (isFirstItem)
{
minItem = item;
isFirstItem = false;
}
else
{
if (item.CompareTo(minItem) < 0)
{
minItem = item;
}
}
}
return minItem;
}
In order to be generic, the method needs TItem to be implementing IComparable. In your case, your Item class could implement like below:
public class Item : IComparable<Item>
{
public string Name { get; set; }
public double Value { get; set; }
public int CompareTo(Item other)
{
return this.Value.CompareTo(other.Value);
}
}
来源:https://stackoverflow.com/questions/23317547/return-item-from-list-with-minimum-value