在C#中使用LINQ进行字典操作 [英] Dictionary Manipulation Using LINQ in C#
本文介绍了在C#中使用LINQ进行字典操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类似的字典
Dictionary<String, List<String>> MyDict = new Dictionary<string, List<string>>
{
{"One",new List<String>{"A","B","C"}},
{"Two",new List<String>{"A","C","D"}}
};
我需要从该词典中获取一个List<String>
,该列表应包含与上述词典中的值不同的项目.
I need to get a List<String>
from this dictionary, The List should contain Distinct items from the values of the above dictionary.
因此,结果列表将包含{"A","B","C","D"}
.
So the resulting List will contain {"A","B","C","D"}
.
现在我正在使用for
循环和Union
操作.喜欢
Now I'm using for
loop and Union
operation. Like
List<String> MyList = new List<string>();
for (int i = 0; i < MyDict.Count; i++)
{
MyList = MyList.Union(MyDict[MyDict.Keys.ToList()[i]]).Distinct().ToList();
}
有人可以建议我在LINQ或LAMBDA表达式中执行此操作吗?
Can any one suggest me a way to do this in LINQ or LAMBDA Expression.
推荐答案
var items=MyDict.Values.SelectMany(x=>x).Distinct().ToList();
或其他选择:
var items = (from pair in MyDict
from s in pair.Value
select s).Distinct().ToList();
这篇关于在C#中使用LINQ进行字典操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文