Return Item from List with Minimum Value

你说的曾经没有我的故事 提交于 2021-02-05 08:09:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!