Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make dictionary case insensitive

Tags:

c#

I am trying to make Dictionary case insensitive. But, I declare it as a property, how can I make that insensitive.

I know that while defining, I can use it like :

var dict = new Dictionary<string, YourClass>(
        StringComparer.InvariantCultureIgnoreCase);

But, I am defining it in my interface and class respectively like

IDictionary<string, string> dict { get; }
public Dictionary<string, string> dict { get; set; }

How can I make this case insensitive ?

like image 744
demo999 89 Avatar asked Feb 27 '26 16:02

demo999 89


2 Answers

You mentioned that You define it in Your class like:

public Dictionary<string, string> dict { get; set; }

So, instead of using short form for auto properties, use the full form:

Dictionary<string, string> _dict = new Dictionary<string, string>(
    StringComparer.InvariantCultureIgnoreCase);
public Dictionary<string, string> dict
{
    get { return _dict; }
    set { _dict = value; }
}

If You are using C# 6.0, You could also probably even write it using the new auto property initializers syntax:

public Dictionary<string, string> dict { get; set; } = new Dictionary<string, string>(
    StringComparer.InvariantCultureIgnoreCase);

Links:

  • C# : How C# 6.0 Simplifies, Clarifies and Condenses Your Code
like image 118
Lukasz M Avatar answered Mar 02 '26 06:03

Lukasz M


The only way you could enforce it on the class or interface level is you make a new derived type and use that type.

public class CaseInsensitiveDictionary<TValue> : Dictionary<string, TValue>
{
    public CaseInsensitiveDictionary() : base(StringComparer.InvariantCultureIgnoreCase)
    {
    }
}

Then in your interface you would do

CaseInsensitiveDictionary<YourClass> { get; }
like image 41
Scott Chamberlain Avatar answered Mar 02 '26 06:03

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!