[英]A case-insensitive list
I need a case insensitive list or set type of collection (of strings). 我需要一个不区分大小写的列表或集合类型的集合(字符串)。 What is the easiest way to create one?
创建一个最简单的方法是什么? You can specify the type of comparison you want to get on the keys of a Dictionary, but I can't find anything similar for a List.
您可以指定要在Dictionary的键上获得的比较类型,但我找不到任何类似的List。
Assuming you're using .NET 3.5, you can just use: 假设您使用的是.NET 3.5,您可以使用:
var strings = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
... or something similar, where you'd pick the appropriate culture setting as well. ...或类似的东西,你也可以选择适当的文化背景。
A list doesn't really have the idea of a comparison for the most part - only when you call IndexOf
and related methods. 只有在调用
IndexOf
和相关方法时,列表才真正具有大部分比较的想法。 I don't believe there's any way of specifying the comparison to use for that. 我不相信有任何方法可以指定用于此的比较。 You could use
List<T>.Find
with a predicate, however. 但是,您可以使用
List<T>.Find
with predicate。
Use Linq, this adds a new method to .Compare 使用Linq,这为.Compare添加了一个新方法
using System.Linq;
using System.Collections.Generic;
List<string> MyList = new List<string>();
MyList.Add(...)
if (MyList.Contains(TestString, StringComparer.CurrentCultureIgnoreCase)) {
//found
}
Looks like its possible to leverage the KeyedCollection class: 看起来可以利用KeyedCollection类:
public class Set<T> : KeyedCollection<T,T>
{
public Set()
{}
public Set(IEqualityComparer<T> comparer) : base(comparer)
{}
public Set(IEnumerable<T> collection)
{
foreach (T elem in collection)
{
Add(elem);
}
}
protected override T GetKeyForItem(T item)
{
return item;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.