views:

112

answers:

3

Given a Generic List of objects that contain a member variable that is a string, what is the best way to get the object that contains the string with the longest length?

ie. assuming val1 is the string I'm comparing:

0 : { val1 = "a"   }
1 : { val1 = "aa"  }
2 : { val1 = "aba" }
3 : { val1 = "c"   }

what needs to be returned is object 2 because "aba" has the greatest length.

+2  A: 

Sorry, I'll try again. You can use the following aggregation:

Dim result = elements.Aggregate(Function(a, b) If(a.val1.Length > b.val1.Length, a, b))
Konrad Rudolph
might need IIF but that looks like it'll work
John Boker
No, I used `If` on purpose! Try it, this construct is new to VB 9. `IIf` is now obsolete.
Konrad Rudolph
i take that back, no IIF needed, it worked :)
John Boker
A: 

You could also use an order-by:

var x = myStringArray.OrderBy(s => s.Length).Last();
Ty
`OrderBy` has the disadvantage of being slower because sorting takes at least O(n logn).
Konrad Rudolph
yes, this is what i initially thought of, this question was asked to me by a co-worker.
John Boker
A: 
Dim longestLength = elements.Max(Function(el) el.val1.Length)
Dim longest = elements.First(Function(el) el.val1.Length = longestLength)
Joe Chung