开发者

Dictionary Manipulation Using LINQ in C#

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"开发者_JAVA百科}}
};

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜