In a List<float[]>
containing arrays of varying sizes, I want to find the Index of that array whose length is maximum in the List.
I'm using the following LINQ statement:
var index = list
.Select((arr, ind) => new { arr, ind })
.Where(x => x.arr.Length == list.Max(a => a.Length))
.Select(x => x.ind)
.ToList()
.First();
This seems to work but the query is returning a list of elements whose Length
is equal to list.Max(a => a.Length)
where after I have to use .First()
to get the first Maximum Index.
Is there any more efficient way to do this so that I directly get the index value rather than a List
to avoid use of First
?
EDIT: As the question was marked duplicate, I want to clarify that I do not want the object in return but the index of that object itself. I've gone through all the posts that my question can be a potential duplicate of and found that they are all returning the object of Max
Length. Though the difference is very thin but I believe my question is not a duplicate.
EDIT: After running a few test and measuring the time taken by each LINQ Satements submitted,Below is the table with time taken (in milliseconds) by each method during my tests
Test | Max | Aggregate | GroupBy | GroupBy OrderByDescending |
---|---|---|---|---|
First | 13.5946 | 1.8927 | 7.3801 | 7.1061 |
Second | 12.3544 | 1.9245 | 7.4852 | 7.1755 |
Third | 12.1003 | 1.8772 | 7.3531 | 6.6891 |
Its easy to understand that Aggregate
method given by Dmitry Bychenko is working far efficiently than any other used methods in this situation. Tim Schmelter's GroupBy
and OrderByDescending
Answer is also doing the same job but taking more time than Aggregate
. Furthermore I wanted to avoid using First
. Hence, I feel the Aggregate
method is an appropriate solution for my question.