从清单中退回具有最小值的项目 [英] Return Item from List with Minimum Value
本文介绍了从清单中退回具有最小值的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个物品清单:
List<Item> items = new List<Item>();
items.add(new Item("cow", 4));
items.add(new Item("pig", 7));
items.add(new Item("dog", 12));
我想用最小的 Value
(其中的数字是那个 Value
)检索该项目.我该怎么办?
I want to retreive the item with the minimum Value
(where the numbers are that Value
). How would I do that?
我正在尝试避免讨厌的 foreach
循环.我正在寻找符合以下条件的东西:
I am trying to avoid a nasty foreach
loop. I am looking for something along the lines of:
return items.Min(Value);
推荐答案
您可以先获取最小值,然后获取具有最小值的项目:
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);
您也可以在效率不高的一行中执行此操作,因为它将对每个项目执行 Min
:
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));
这篇关于从清单中退回具有最小值的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文