在C#中使用LINQ进行字典操作[英] Dictionary Manipulation Using LINQ in C#

本文是小编为大家收集整理的关于在C#中使用LINQ进行字典操作的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一本像

这样的字典
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();

本文地址:https://www.itbaoku.cn/post/1556772.html

问题描述

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();