2

我有以下方法用来自数据阅读器的值填充字典。数据读取器字段和传递给方法的属性之间可能存在大小写不匹配。在以下方法中,我首先将属性转换为小写以解决此问题。这会导致两个字典。有没有更好的方法可以用一本字典来实现这一目标?

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;
}
4

2 回答 2

7

您可以忽略大小写DictionaryDictionary具有接受的重载构造函数IEqualityComparerStringComparer.InvariantCultureIgnoreCase用于忽略键的大小写敏感:

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

因此,只有一本带有忽略大小写的字典就足以满足您的代码

于 2012-11-06T08:25:16.290 回答
1

感谢@CuongLe。如果您喜欢以下内容,请点赞@Cuong Le 回答。

为了他人的利益,我将在这里写下答案:

    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;
    }

参考:

  1. 不区分大小写的列表搜索
于 2012-11-06T09:10:58.087 回答