Retrieve an object that has a member variable with the longest string length
-
05-07-2019 - |
Question
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.
Solution
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))
OTHER TIPS
You could also use an order-by:
var x = myStringArray.OrderBy(s => s.Length).Last();
Dim longestLength = elements.Max(Function(el) el.val1.Length)
Dim longest = elements.First(Function(el) el.val1.Length = longestLength)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow