views:

32

answers:

1

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.

+6  A: 
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();
Marc Gravell
Aw, you beat me :p. The Linq questions are always fun.
Rei Miyasaka