Wanted: .Net collection that stores a bunch of case insensitive strings fast and efficient
I'm looking for a simple collection that will store a bunch of strings in a case insensitive way开发者_运维百科. I need at least a Contains()
and Remove()
method to see if a certain string is present and to remove that string.
I've tried List<string>
but that one is case sensitive. I need could use a case insensitive Dictionary<TKey, T>
, but that "feels" like a waste of space. Doing a ToLower()
on each string is a waste of performance.
Does anyone know what kind .Net collection I should use?
You should use a new HashSet<string>(StringComparer.OrdinalIgnoreCase)
.
Note that this is an unordered set.
You could use a StringDictionary
.
Had the same problem to solve today. If you can include Linq, then your List gets overloaded methods with a comparer.
using System.Linq;
List<string> stringList = new List<string>();
stringList.Contains("hello", StringComparer.OrdinalIgnoreCase);
Hope this helps: Martin
By default Dictionary are not case in-sensitive. But you can implement your own variant to make it in-sensitive. (I might be wrong on this :D)
I had same issue with Dictionary but then after trying a lot of IEquality implementations, finally I settled the score with LINQ.
string k = customers.Where(c => c.Key.Equals(valueToSearch, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().Key;
if (!string.IsNullOrEmpty(k) && k.ToUpper() == valueToSearch.ToUpper())
{
// Do some thing
}
Hope this will help somebody in future.
Sanjay Zalke
Write your own Contains()
and Remove()
methods, which perform the case insensitve comparison.
精彩评论