我有两个 Dictionary<string, Item>
秒。 Item
有一个有公共(public)属性(property)int Level
.
我想结合这两个字典,其中键是唯一的,我希望能够在两者上指定级别。
有点像
dictionary 1 = all items that level < 10 dictionary 2 = all items level < 20 combine dictionary 2 with 1 (where Value.Level < 10) if the Key is unique and the Value.Level < 20
I can easily do this with foreach loops. I can also do this with multiple linq queries. However i can't seem to figure out how to make this one single linq query.
Edit- Per your request John here is the code with foreach
Dictionary<string, Dictionary<string, Item>> itemDictionary = new Dictionary<string, Dictionary<string, Item>>();
Dictionary<string, Item> items = new Dictionary<string,Item>();
if (itemDictionary.ContainsKey(comboBox.Text))
{
foreach (KeyValuePair<string, Item> kvp in itemDictionary[comboBox.Text])
{
if (!items.ContainsKey(kvp.Key) && kvp.Value.Level <= int.Parse(textBox.Text))
items.Add(kvp.Key, kvp.Value);
}
}
if (itemDictionary.ContainsKey(comboBox1.Text))
{
foreach (KeyValuePair<string, Spell> kvp in itemDictionary[comboBox1.Text])
{
if (!items.ContainsKey(kvp.Key) && kvp.Value.Level <= int.Parse(textBox1.Text))
items.Add(kvp.Key, kvp.Value);
}
}
var query = from s in items
orderby s.Value.Level
select s;
foreach (var i in query)
listBox.Items.Add(string.Format("{0} {1}", i.Value.Level, i.Key));
最佳答案
如果您可以轻松地在 foreach 循环中执行您想要的操作,那么您已经编写了代码。这告诉我,foreach 代码可能比复杂的 LINQ 查询更具可读性和更易于维护。
这听起来像是保留 foreach 循环代码的完美案例。 LINQ 可能更新,但这并不总是意味着它更好。
关于c# linq combine 2 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126240/