Skip to content

Instantly share code, notes, and snippets.

@snboisen
Created July 7, 2015 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snboisen/fbf4cc7106c6ee55c136 to your computer and use it in GitHub Desktop.
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#
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