int[] num = {1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1};
How do I use LINQ to get the Max value and the index of the Max value between index 3 and index 8?
int[] num = {1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1};
How do I use LINQ to get the Max value and the index of the Max value between index 3 and index 8?
You can use:
var info = num.Select( (i, ind) => new {Value=i, Index=ind}).Skip(3).Take(6) .OrderByDescending(p => p.Value).First(); Console.WriteLine("Value {0} at Index {1}", info.Value, info.Index); You could also use Aggregate:
var info = num.Select( (i, ind) => new {Value=i, Index=ind}).Skip(3).Take(6) .Aggregate((a, b) => b.Value > a.Value ? b : a); This can be simplified if you use MoreLinq's MaxBy() or a similar routine to something a bit nicer:
var info = num.Select( (i, ind) => {Value=i, Index=ind}).Skip(3).Take(6) .MaxBy(p => p.Value); .OrderByDescending(...).First(), you could use .Aggregate((a,p) => (a.Value > p.Value) ? a : p). Aggregate is specifically for these types of scenarios.Give this a try. It's not a single query but may help.
var max = num.Skip(3).Take(4).Max(); var indexOfItem = num.Skip(3).Take(4).First(t => t.Equals(max)); // this is not correct, returns the value not the index. First is going to return the item, not the index of the item... The above code would return 9,9, not 9,8 (with Take(6)).