Converting Lookup<TKey, TElement> into other data structures c#

FSm picture FSm · Jul 8, 2012 · Viewed 10.7k times · Source

I have a

Lookup<TKey, TElement>

where the TElement refers to a string of words. I want to convert Lookup into:

Dictionary<int ,string []> or List<List<string>> ?

I have read some articles about using the

Lookup<TKey, TElement>

but it wasn't enough for me to understand. Thanks in advance.

Answer

Philip Daubmeier picture Philip Daubmeier · Jul 8, 2012

You can do that using these methods:

Lets say you have a Lookup<int, string> called mylookup with the strings containing several words, then you can put the IGrouping values into a string[] and pack the whole thing into a dictionary:

var mydict = mylookup.ToDictionary(x => x.Key, x => x.ToArray());

Update

Having read your comment, I know what you actually want to do with your lookup (see the ops previous question). You dont have to convert it into a dictionary or list. Just use the lookup directly:

var wordlist = " aa bb cc ccc ddd ddd aa ";
var lookup = wordlist.Trim().Split().Distinct().ToLookup(word => word.Length);

foreach (var grouping in lookup.OrderBy(x => x.Key))
{
    // grouping.Key contains the word length of the group
    Console.WriteLine("Words with length {0}:", grouping.Key);

    foreach (var word in grouping.OrderBy(x => x))
    {
        // do something with every word in the group
        Console.WriteLine(word);
    }
}

Also, if the order is important, you can always sort the IEnumerables via the OrderBy or OrderByDescending extension methods.

Edit:

look at the edited code sample above: If you want to order the keys, just use the OrderBy method. The same way you could order the words alphabetically by using grouping.OrderBy(x => x).