Converting Lookup into other data structures

2019-04-06 16:28发布

问题:

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.

回答1:

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



回答2:

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


标签: c# c#-4.0 lookup