General comparison of dictionaries
I have a problem that I don't seem to wrap my head around. I am creating a class to store a dictionary of items that have common types. The problem I am facing is needed to get this dictionary to be InvariantCultureIgnoreCase
if the index type is string.
For example:
public class Cache<TIndex, TItem>
{
protected IDictionary<TIndex, TItem> _cache { get; set; }
public Cache()
{
this._cache = new Dictionary<TIndex, TItem>();
}
public bool Exists(TIndex index)
{
if (!_cache.ContainsKey(index))
{
//....do other stuff here
this._cache.Add(databaseResult.Key, databaseResult.Value);
return false;
}
return true;
}
}
So, the first problem was about strings with different capitalizations; I solved this by forcing the data to be uppercase. Now, however, I found that there are some characters that are culture specific, so without switching the invariant culture ContainsKey
will return false.
I tried creating a new one IEqualityComparer
, but this never starts. Any ideas?
source to share
Try the following:
public Cache()
{
if (typeof(TIndex) == typeof(string))
{
this._cache = new Dictionary<TIndex, TItem>((IEqualityComparer<TIndex>)StringComparer.InvariantCultureIgnoreCase);
}
else
{
this._cache = new Dictionary<TIndex, TItem>();
}
}
Or (with a ternary operator):
public Cache()
{
this._cache = typeof(TIndex) == typeof(string)
? new Dictionary<TIndex, TItem>((IEqualityComparer<TIndex>)StringComparer.InvariantCultureIgnoreCase)
: new Dictionary<TIndex, TItem>();
}
Or (really short as @Rawling suggested):
public Cache()
{
this._cache = new Dictionary<TIndex, TItem>(StringComparer.InvariantCultureIgnoreCase as IEqualityComparer<TIndex>);
}
source to share
Here's a fully functional version of what I THINK you are asking for (I had to add the Set function, otherwise it will be based on your own code). This is as shown by checking if / Console.WriteLine, ignoring case. If this is not what you are looking for, please clarify your question.
class Program
{
static void Main(string[] args)
{
Cache<string, string> stringCache = new Cache<string, string>();
stringCache.Set("A String Index", "A String Item");
if (stringCache.Exists("A String Index"))
Console.WriteLine("Title Case exists");
if (stringCache.Exists("A STRING INDEX"))
Console.WriteLine("All Caps Exists");
if (stringCache.Exists("a string index"))
Console.WriteLine("All Lowercase Exists");
}
}
class Cache<TIndex, TItem>
{
private IDictionary<TIndex, TItem> _cache { get; set; }
public Cache()
{
if (typeof(TIndex) == typeof(string))
{
_cache = new Dictionary<TIndex, TItem>((IEqualityComparer<TIndex>)StringComparer.InvariantCultureIgnoreCase);
}
else
{
_cache = new Dictionary<TIndex, TItem>();
}
}
public void Set(TIndex index, TItem item)
{
_cache[index] = item;
}
public bool Exists(TIndex index)
{
if (!_cache.ContainsKey(index))
{
return false;
}
return true;
}
}
source to share