我有以下方法用数据阅读器中的值填充字典。数据读取器字段与传递给方法的属性之间可能存在不匹配的情况。在下面的方法中,我首先将属性转换为小写以解决此问题。这会导致两个词典。有没有更好的方法来实现这一目的?
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;
}
答案 0 :(得分:7)
您可以忽略Dictionary
中的案例,Dictionary
有一个overload constructor接受IEqualityComparer
,使用StringComparer.InvariantCultureIgnoreCase
忽略区分大小写的密钥:
var dic =
new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
因此,只有一个带有忽略大小写的字典足以支持您的代码
答案 1 :(得分:1)
感谢@CuongLe。如果你喜欢以下内容,请upvote @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;
}
参考: