How to determine the greatest value in a collection of items?
Using the following simple Item class:
class Item
{
public int Value { get; set; }
}
And this list of items:
var items = new List<Item>();
items.Add( new Item() { Value = 1 } );
items.Add( new Item() { Value =开发者_高级运维 2 } );
items.Add( new Item() { Value = 3 } );
How to tell the greatest value in all items?
How to determine which Item in the list has the greatest value?
Using LINQ
items.Max(v => v.Value)
Items containing greatest value
var max = items.Max(v => v.Value);
var x = items.Where(v => v.Value == max);
However, MaxBy extension method suggested by devdigital will iterate the collection only once
And how to directly tell the greatest value in all items?
You can use the Max
standard query operator:
var maxValue = items.Max(i => i.Value);
How to determine which Item in the list has the greatest value?
Check out morelinq for the MaxBy
extension
Enumerable.max:
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.max.aspx
public class ItemEvaluator
{
public int Highest { get { return highest; } }
public int Lowest { get { return lowest; } }
public void Add(Item item)
{
highest = item.Value > highest ? item.Value : highest;
lowest = item.Value < lowest ? item.Value : lowest;
items.Add(items);
}
private List<int> items = new List<int>();
private int lowest;
private int highest;
}
public class Item
{
public int Value { get; set; }
}
精彩评论