List<string>.Contains using trim

It would be nice if this worked, but alas it doesn't.

List<string> items = new List<string>();
items.Add("a ");
bool useTrim = true;
if (items.Contains("a", useTrim)) {
    Console.WriteLine("I'm happy");
}

I ended up implementing it as an extension method below. But I was wondering if anyone else had any elegant ideas other than creating a comparer class or looping through.

/// <summary>
/// Determines whether an element in the List of strings 
/// matches the item. .Trim() is applied to each element
/// for the comparison
/// </summary>
/// <param name="value">a list of strings</param>
/// <param name="item">the string to search for in the list</param>
/// <returns>true if item is found in the list</returns>
public static bool ContainsTrimmed(this List<string> value, string item) {
    bool ret = false;
    if ((value.FindIndex(s => s.Trim() == item)) >= 0) {
        ret = true;
    }
    return ret;
}
Jon Skeet
people
quotationmark

Well you'll either need to loop through it each time, or create another list of just the trimmed values, and use that for searching. (Heck, you could create a HashSet<string> if you only need to know whether or not a trimmed value is present.)

However, if you want to stick to just a single list, then rather than using FindIndex I'd use Any from LINQ:

if (items.Any(x => x.Trim() == item))

Note that even if you do want to keep your ContainsTrimmed method, you can simplify it to just:

return value.FindIndex(s => s.Trim() == item) >= 0;

people

See more on this question at Stackoverflow