2014-10-29 123 views
0

如何从不同的数据表调用中读取特定类型成员的字典?加载特定类型的字典值

  1. 我使用的方法HashSet.ToDictionary
  2. 然后我打电话给DB和要加载的对象(属性值1)
  3. 最后,我将调用另一个数据库,发现和预填入填充字典现有对象的Value2属性
HashSet <string> hashset = new HashSet <string>(); 
Dictionary < string, CustomeObject > dictionary = new Dictionary < string, CustomeObject >(); 
dictionary = hashset.ToDictionary(h => h, h => (CustomeObject) null); 
while (firstreader.Read()) { 
    if (dictionary.ContainsKey(firstreader.GetValue(1).ToString())) { 
    dictionary[firstreader.GetValue(1).ToString()] = new CustomeObject() { 
     Key = firstreader.GetValue(1).ToString(), 
     Value1 = firstreader.GetValue(2).ToString(), 
     Value2 = null 
    }; 
    } 
} 


while (secondreader.Read()) { 
    if (dictionary.ContainsKey(secondreader.GetValue(1).ToString())) { 
    dictionary[secondreader.GetValue(1).ToString()] = new CustomeObject() { 
     Key = "", //Persist the value from previous load 
     Value1 = secondreader.GetValue(2).ToString(), 
     Value2 = null; 
    }; 
    } 
} 

回答

0

当你写的字典,同时通过两个迭代的读者,你是一个实例新对象并将其分配给字典值。因此,您在读取firstreader时创建对象,然后在读取secondreader时覆盖该对象。

阅读secondreader时需要做的是检查字典值是否为空。如果不是,那就写Value2。

while (secondreader.Read()) { 
    var myReadValue = secondreader.GetValue(1).ToString(); 
    if (dictionary.ContainsKey(myReadValue)) { 
    if(dictionary[myReadValue] != null) { 
     dictionary[myReadValue].Value2 = secondreader.GetValue(2).ToString(); 
    } 
    } 
}