3

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?

4
  • 1
    duplicate stackoverflow.com/questions/8661097/… Commented Dec 28, 2011 at 21:21
  • No, that question is just to get the max, I am also looking to get the index of the max value in the array Commented Dec 28, 2011 at 21:23
  • this question contains nearly the same text as your other question. The philosophy here is to try it yourself, post an example of what you tried and what internet research you came up with, and then describe your problem in detail. I don't see any research effort. Commented Dec 28, 2011 at 21:27
  • There can be multiple indices if there are duplicate max elements. Commented Dec 28, 2011 at 21:33

2 Answers 2

3

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

Better than .OrderByDescending(...).First(), you could use .Aggregate((a,p) => (a.Value > p.Value) ? a : p). Aggregate is specifically for these types of scenarios.
0

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. 

1 Comment

Two things: Should take >4 (6 for 8 inclusive) if you want to get the proper number of elements. Second, 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)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.