简体   繁体   中英

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;
}

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;

I would suggest creating a custom IEqualityComparer to supply to the overloaded function Contains . This is exactly the reason why this overload exists.

class TrimmedEqualityComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        if (x == null && y != null || x != null && y == null)
            return false;
        if (x == null && y == null)
            return true;
        return x.Trim() == y.Trim();
    }

    public int GetHashCode(string obj)
    {
        return obj != null ? obj.GetHashCode() : 0;
    }
}

You call it like this.

    var strs = new string[] {"a  ", "b  ", "c"};
    if (strs.Contains("b", new TrimmedEqualityComparer()))
        Console.WriteLine("I'm happy");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM