Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

lookup

c#-4.0

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.

like image 897
FSm Avatar asked Jul 08 '12 13:07

FSm


2 Answers

You can do that using these methods:

  • Enumerable.ToDictionary<TSource, TKey>
  • Enumerable.ToList<TSource>

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).

like image 71
Philip Daubmeier Avatar answered Sep 23 '22 08:09

Philip Daubmeier


A lookup is a collection of mappings from a key to a collection of values. Given a key you can get the collection of associated values:

TKey key;
Lookup<TKey, TValue> lookup;
IEnumerable<TValue> values = lookup[key];

As it implements IEnumerable<IGrouping<TKey, TValue>> you can use the enumerable extension methods to transform it to your desired structures:

Lookup<int, string> lookup = //whatever
Dictionary<int,string[]> dict = lookup.ToDictionary(grp => grp.Key, grp => grp.ToArray());
List<List<string>> lists = lookup.Select(grp => grp.ToList()).ToList();
like image 41
Lee Avatar answered Sep 22 '22 08:09

Lee