Tas*_*han 67 c# string hashset
如何HashSet<string>.Contains()在案例敏感模式下使用方法?
Joã*_*elo 113
您可以HashSet使用自定义比较器创建:
HashSet<string> hs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
hs.Add("Hello");
Console.WriteLine(hs.Contains("HeLLo"));
Run Code Online (Sandbox Code Playgroud)
Kob*_*obi 10
您需要使用右侧创建它IEqualityComparer:
HashSet<string> hashset = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)
这里没有必要,正如其他答案所证明的那样,但在其他不使用字符串的情况下,您可以选择实现一个IEqualityComparer<T>,然后就可以使用.Contains重载.下面是一个使用字符串的示例(同样,其他答案表明已经有一个符合您需求的字符串比较器).许多方法IEnumerable<T>都有接受这种比较器的重载,所以学习如何实现它们是很好的.
class CustomStringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return x.Equals(y, StringComparison.InvariantCultureIgnoreCase);
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用它
bool contains = hash.Contains("foo", new CustomStringComparer());
Run Code Online (Sandbox Code Playgroud)
您应该使用允许您指定要使用的构造函数IEqualityComparer.
HashSet<String> hashSet = new HashSet<String>(StringComparer.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)
所述StringComparer对象提供了一些经常使用的比较器作为静态属性.
| 归档时间: |
|
| 查看次数: |
34294 次 |
| 最近记录: |