2010-10-23 82 views
2

我有一个字典使用LINQ像字典操纵在C#

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>,列表中应包含上述字典的值鲜明的项目。

所以得到的列表将包含{"A","B","C","D"}

现在我使用for循环和Union操作。像

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表达式中做到这一点。

回答

7
var items=MyDict.Values.SelectMany(x=>x).Distinct().ToList(); 

或替代:

var items = (from pair in MyDict 
      from s in pair.Value 
      select s).Distinct().ToList(); 
+0

哦,你打我:对。 Linq的问题总是很有趣。 – 2010-10-23 09:25:35