Created
July 7, 2015 15:51
-
-
Save snboisen/fbf4cc7106c6ee55c136 to your computer and use it in GitHub Desktop.
Two ways to find index of longest string in a collection of strings in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using NUnit.Framework; | |
namespace Async.Model.UnitTest | |
{ | |
public class FindIndexTest | |
{ | |
public struct LengthAndIndex | |
{ | |
public int CurrentIndex; | |
public int MaxLenght; | |
public int IndexOfMaxLen; | |
} | |
public int FindIndexOfLongestItem(IEnumerable<string> items) | |
{ | |
var initialMaxLengthAndIndex = new LengthAndIndex() { CurrentIndex = -1, MaxLenght = -1, IndexOfMaxLen = -1 }; | |
return items.Aggregate(initialMaxLengthAndIndex, (max, val) => | |
{ | |
max.CurrentIndex++; | |
if (val.Length > max.MaxLenght) | |
{ | |
max.MaxLenght = val.Length; | |
max.IndexOfMaxLen = max.CurrentIndex; | |
} | |
return max; | |
}, max => max.IndexOfMaxLen); | |
} | |
[Test] | |
public void FindIndexOfLongestElementWorks() | |
{ | |
IList<string> haystack = new List<string>() { "hej", "med", "diiiiiiiiiig", "mand" }; | |
int indexOfMax = FindIndexOfLongestItem(haystack); | |
Assert.That(indexOfMax, Is.EqualTo(2)); | |
} | |
public int FindIndexOfLongestItemAlt(List<string> items) | |
{ | |
int maxLen = items.Max(item => item.Length); | |
return items.FindIndex(item => item.Length == maxLen); | |
} | |
[Test] | |
public void AlternativeFindIndexOfLongestElementWorks() | |
{ | |
IList<string> haystack = new List<string>() { "hej", "med", "diiiiiiiiiig", "mand" }; | |
int indexOfMax = FindIndexOfLongestItem(haystack); | |
Assert.That(indexOfMax, Is.EqualTo(2)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment