2014-03-06 24 views
0

如果这能够起作用,那将会很好,但是它不会。列表<string>。使用调整的包含

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

我最终将它作为下面的扩展方法实现。但是我想知道除了创建比较器类或循环以外,其他人是否有任何优雅的想法。

/// <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; 
} 
+3

这里有问题吗? – czuroski

回答

4

那么你需要每次都循环遍历它,或者创建另一个只是修剪后的值的列表,并将其用于搜索。 (哎呀,你可以创建一个HashSet<string>,如果你只需要知道一个修整值是否不存在。)

但是,如果你想坚持到只是一个单一的列表,然后而不是使用FindIndex我会使用Any从LINQ:

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

请注意,即使你做要保持你的ContainsTrimmed方法,可以将其简化到只是:

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

它不是无效的(而常规的“包含”是) –

+0

@Konrad:OP的方法不是,所以我认为这不是必需的。 –

+0

我喜欢。任何。我知道我脑筋痉挛,错过了一个简单的解决方案。谢谢。我没有看到任何将它标记为答案的方法。 – user3388725

1

我会sugge st创建自定义IEqualityComparer以供应超载函数Contains。 这正是此超载存在的原因。

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

你这样称呼它。

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