问题描述
我有一本像
这样的字典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 表达式中执行此操作的方法.
推荐答案
var items=MyDict.Values.SelectMany(x=>x).Distinct().ToList();
或替代方案:
var items = (from pair in MyDict from s in pair.Value select s).Distinct().ToList();
问题描述
I'm having a Dictionary like
Dictionary<String, List<String>> MyDict = new Dictionary<string, List<string>> { {"One",new List<String>{"A","B","C"}}, {"Two",new List<String>{"A","C","D"}} };
I need to get a List<String> from this dictionary, The List should contain Distinct items from the values of the above dictionary.
So the resulting List will contain {"A","B","C","D"}.
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(); }
Can any one suggest me a way to do this in LINQ or LAMBDA Expression.
推荐答案
var items=MyDict.Values.SelectMany(x=>x).Distinct().ToList();
Or an alternative:
var items = (from pair in MyDict from s in pair.Value select s).Distinct().ToList();
相关问答
相关标签/搜索