问题描述
我有方法,HashSet的参数。而我需要做的不区分大小写的范围内它包含:
公共无效DoSomething的(HashSet的<串>设置,串项)
{
变种X = set.Contains(项目);
:
}
这是任何方式使现有的HashSet的情况下,不敏感(不创建新的)?
我在寻找最佳的解决方案性能比较
修改
包含可以被多次调用。所以IEnumerable的扩展不适合我接受,由于比天然HashSet的低性能比较包含的方法。
解决方案
一直以来,回答我的问题是NO,这是不可能的,我已经创建并使用下面的方法:
公开的HashSet<串GT; EnsureCaseInsensitive(HashSet的<串GT;集)
{
返回set.Comparer == StringComparer.OrdinalIgnoreCase
?集
:新的HashSet<串GT;(套,StringComparer.OrdinalIgnoreCase);
}
的 HashSet的< T>
构造函数的重载,可以让你在自定义传的IEqualityComparer<串GT;
。有几个这些为您定义已在静态 StringComparer
类,其中的一些忽略大小写。例如:
VAR集=新的HashSet<串GT;(StringComparer.OrdinalIgnoreCase);
set.Add(约翰);
Debug.Assert的(set.Contains(约翰));
您将不得不作出在建造时这一变化的 HashSet的< ; T>
。一旦一个人存在,你不能改变的的IEqualityComparer< T>
它的使用
只要你知道,在默认情况下(如果你不传递任何的IEqualityComparer< T>
到的HashSet< T> ;
构造函数),它使用 EqualityComparer< T> .DEFAULT
而不是
修改
这个问题看来我贴我的回答后,已经改变了。如果你必须做一个案例的不区分大小写的在现有的情况下,搜寻的敏感的的HashSet<串>
,你将不得不做线性搜索:
set.Any(S = GT; string.Equals(S,项目,StringComparison.OrdinalIgnoreCase)) ;
有没有办法解决这个。
I have method with HashSet parameter. And I need to do case-insensitive Contains within it:
public void DoSomething(HashSet<string> set, string item)
{
var x = set.Contains(item);
...
}
Is it any way to make existing HashSet case-insensitive (do not create new one)?
I'm looking for solution with best perfomance.
Edit
Contains can be called multiple times. So IEnumerable extensions are not acceptable for me due to lower perfomance than native HashSet Contains method.
Solution
Since, answer to my question is NO, it is impossible, I've created and used following method:
public HashSet<string> EnsureCaseInsensitive(HashSet<string> set)
{
return set.Comparer == StringComparer.OrdinalIgnoreCase
? set
: new HashSet<string>(set, StringComparer.OrdinalIgnoreCase);
}
The HashSet<T>
constructor has an overload that lets you pass in a custom IEqualityComparer<string>
. There are a few of these defined for you already in the static StringComparer
class, a few of which ignore case. For example:
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
set.Add("john");
Debug.Assert(set.Contains("JohN"));
You'll have to make this change at the time of constructing the HashSet<T>
. Once one exists, you can't change the IEqualityComparer<T>
it's using.
Just so you know, by default (if you don't pass in any IEqualityComparer<T>
to the HashSet<T>
constructor), it uses EqualityComparer<T>.Default
instead.
Edit
The question appears to have changed after I posted my answer. If you have to do a case insensitive search in an existing case sensitive HashSet<string>
, you will have to do a linear search:
set.Any(s => string.Equals(s, item, StringComparison.OrdinalIgnoreCase));
There's no way around this.
这篇关于C#:请HashSet的<串GT;不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!