LCJ
LCJ

Reputation: 22661

Better code for avoiding one dictionary - Case Sensitivity Issue

I have following method to fill a dictionary with values from a data reader. There can be case mismatches between the data-reader fields and properties passed to the method. In the following method I am converting the properties to lowercase first to address this issue. This causes two dictionaries. Is there a better way to achieve this with one dictionary?

private Dictionary<string, object> FillDictionaryWithReaderValues(List<string> propertiesOfAllEntities, IDataReader reader)
{
   Dictionary<string, object> lowerCaseDictionary = new Dictionary<string, object>();
   Dictionary<string, object> propertyResultList = new Dictionary<string, object>();

   foreach (var item in propertiesOfAllEntities)
   {
      lowerCaseDictionary.Add(item.ToLower(), null);
   }

   for (int i = 0; i < reader.FieldCount; i++)
   {
      lowerCaseDictionary[reader.GetName(i).ToLower()] = reader[i];
   }

   foreach (var item in propertiesOfAllEntities)
   {
      propertyResultList.Add(item, lowerCaseDictionary[item.ToLower()]);
   }

   return propertyResultList;
}

Upvotes: 2

Views: 246

Answers (2)

cuongle
cuongle

Reputation: 75316

You can ignore case in Dictionary, Dictionary has an overload constructor which accepts IEqualityComparer, use StringComparer.InvariantCultureIgnoreCase to ignore case-sensitive for key:

var dic = 
      new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);

So only one dictionary with ignore case is enough for your code

Upvotes: 7

LCJ
LCJ

Reputation: 22661

Thanks to @CuongLe. Please upvote @Cuong Le answer if you like the following.

For the benefit of others I will write the answer here:

    private Dictionary<string, object> FillDictionaryWithReaderValues(List<string> propertiesOfAllEntities, IDataReader reader)
    {

        Dictionary<string, object> propertyResultList = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
        for (int i = 0; i < reader.FieldCount; i++)
        {
            string readerFieldName = reader.GetName(i);
            //Whether propertiesOfAllEntities.Contains the property
            if (propertiesOfAllEntities.FindIndex(x => x.Equals(readerFieldName, StringComparison.OrdinalIgnoreCase)) != -1)
            {
                propertyResultList.Add(readerFieldName, reader[i]);
            }

        }

        return propertyResultList;
    }

REFERENCE:

  1. Case-Insensitive List Search

Upvotes: 1

Related Questions