开发者

Dictionary Manipulation Using LINQ in C#

开发者 https://www.devze.com 2023-01-21 06:06 出处:网络
I\'m having a Dictionary like Dictionary<String, List<String>> MyDict = new Dictionary<string, List<string>>

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

精彩评论

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