Better code for avoiding one dictionary - Case Sensitivity Issue
我有以下方法用数据阅读器中的值填充字典。数据读取器字段和传递给方法的属性之间可能存在大小写不匹配。在下面的方法中,我首先将属性转换为小写,以解决这个问题。这导致了两部词典。有没有更好的方法来实现这一点与一本字典?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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; } |
在
1 2 |
所以只有一个带忽略大小写的字典就足够了
感谢@cuongle。如果您喜欢以下内容,请向上投票@cuong le回答。
为了其他人的利益,我将在这里写下答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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; } |
参考文献: