Converting Lookup into other data structures c#

后端 未结 2 1739
别那么骄傲
别那么骄傲 2021-01-04 10:27

I have a

Lookup

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



        
相关标签:
2条回答
  • 2021-01-04 11:05

    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();
    
    0 讨论(0)
  • 2021-01-04 11:09

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

    0 讨论(0)
提交回复
热议问题