Take a desired string, iterate through objects to see if it exists in a given field and append a number until a unique string is found

I wanted to in the most generic way possible write a method in C# to achieve the following.

  • Take in a string, a set of objects, and a function to access the field of a given object
  • Look at all of the strings from the fields of these objects to match against provided string
  • If provided string is not unique in a case insensitive manner, append _x to the end, where x is an incrementing integer until a unique string is found

With that in mind, I created this.

private string GetUniqueStringForModel<T>(string originalString, IEnumerable<T> enumerableObjects, Func<T, string> stringFieldFunction) where T : class {     var uniqueString = originalString;     var duplicateCount = 1;      while (enumerableObjects.Select(stringFieldFunction).ToList().Any(currentString => string.Equals(currentString, uniqueString, StringComparison.InvariantCultureIgnoreCase)))     {         uniqueString = originalString + "_" + duplicateCount++;     }      return uniqueString; } 

I would rather have not put the ToList() in but when working with Entity Framework it was complaining about doing the string comparison in LINQ (presumably because it couldn’t compile it SQL).

Any thoughts or ideas for improvement?