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

强颜欢笑 提交于 2020-01-21 04:21:04

问题


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


来源:https://stackoverflow.com/questions/11383384/converting-lookuptkey-telement-into-other-data-structures-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!