【问题标题】:Dictionary Manipulation Using LINQ in C#在 C# 中使用 LINQ 进行字典操作
【发布时间】:2010-10-23 09:19:44
【问题描述】:

我有一本像

这样的字典
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&lt;String&gt;,列表应该包含来自上述字典值的不同项目。

所以结果列表将包含{"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 表达式中执行此操作的方法。

【问题讨论】:

    标签: c# linq dictionary lambda


    【解决方案1】:
    var items=MyDict.Values.SelectMany(x=>x).Distinct().ToList();
    

    或替代方案:

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

    【讨论】:

    • 噢,你打败了我:p。 Linq 问题总是很有趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多