我有一个包含字符串作为 TKey 和一个类“组件”作为 TValue 的字典。我的问题是想要将数据库值和 xml 值添加到类字段中。
这是我的类组件:
public class Component
{
public string ComponentNr { get; set; }
public string Omschrijving { get; set; }
public int Aantal { get; set; }
public int Pos { get; set; }
}
我已经用 xml 属性值填充了 ComponentNr 和 Pos 字段,现在我想从数据库中获取“Aantal”和“Omschrijving”,其中数据库值“artcode”是 ComponentNr
查询:
SqlCommand dgCommand = new SqlCommand("select g.artcode, i.Description, sum(g.aantal*-1) as aantal " +
"from gbkmut g " +
"join Items i on g.artcode = i.ItemCode " +
"where 1=1 and g.project=@projectnr and g.reknr=3000 and g.bud_vers='MRP' and g.operation='VOORSMD' and g.artcode !='H MAN' and i.Description not like 'pcb %' " +
"group by g.artcode, i.Description, g.aantal ", conn);
这就是我现在用 xml 属性值填充字典的方法:
Dictionary<string, Component> resultaten = componenten;
List<string> files = fileList;
string file;
file = files.Find(x => x.Contains(faberNr));
XDocument xdoc = XDocument.Load(file);
List<Component> components = xdoc.Descendants("Part").Select(x => new Component()
{
ComponentNr = (string)x.Elements().Where(y => y.Attribute("PartsName") != null)
.Select(y => (string)y.Attribute("PartsName")).FirstOrDefault(),
Pos = (int)x.Descendants().Where(y => y.Attribute("Setno") != null)
.Select(y => (int)y.Attribute("Setno")).FirstOrDefault()
}).ToList();
resultaten = components.GroupBy(x => x.ComponentNr, y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
return resultaten;
示例:
我的预期输出是:
Key = 38292000
Value = Component
Aantal = 16
ComponentNr = 38292000
Omschrijving = Omschrijving123
Pos = 12
我的实际输出是:
Key = 38292000
Value = Component
Aantal = 0
ComponentNr = 38292000
Omschrijving = null
Pos = 12
因此,第 1 步是Dictionary<string, Component>
从 xml填充 a 。然后第 2 步是运行数据库查询以完成填写Component
存储在Dictionary
?
ComponentNr
是进入 的键Dictionary
,并且您ComponentNr
从"artcode"
字段中的数据库查询中获得,因此您只需从Dictionary
using查找值"artcode"
然后修改它。
// reader is an instance of SqlDataReader you got from the SqlCommand.
// resultaten is the Dictionary<string, Component> that you populated earlier.
// If these columns can be null in the database, don't forget to check them for DBNull.Value.
string componentNr = Convert.ToString(reader["artcode"]);
if (resultaten.TryGetValue(componentNr, out Component value))
{
value.Aantal = Convert.ToInt32(reader["aantal"]);
value.Omschrijving = Convert.ToString(reader["Description"]);
}
else
{
// Component exists in the database but not in the Dictionary.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句