Skip to content

Instantly share code, notes, and snippets.

@Larry57
Created October 17, 2013 07:41
Show Gist options
  • Save Larry57/7020728 to your computer and use it in GitHub Desktop.
Save Larry57/7020728 to your computer and use it in GitHub Desktop.
Returns a new unique key from an existing IEnumerable<string>. The key is based on a prefix followed by a number. For example, in "Customer_0", "Customer_1", "Customer_4"..., GetUniqueKey will return "Customer_2".
public static class Extensions
{
public static string GetUniqueKey(this IEnumerable<string> keys, string prefix, StringComparison comparisonType = StringComparison.InvariantCultureIgnoreCase)
{
int count = 0;
while (keys.FirstOrDefault(k => k.StartsWith(prefix + count, comparisonType)) != null)
count++;
return prefix + count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment