Convert Lookup <TKey, TElement> to other C # data structures

I have

Lookup<TKey, TElement> 

where TElement refers to a string of words. I want to convert Search in:

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

I read several articles about using

 Lookup<TKey, TElement> 

but that was not enough for me. Thanks in advance.

+7
source share
2 answers

You can do this using the following methods:

Suppose you have a Lookup<int, string> called mylookup with strings containing multiple words, then you can put the IGrouping values ​​in string[] and pack it all into a dictionary:

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

Update

After reading my comment, I know what you really want to do with your search (see ops previous question ). You do not need to convert it to a dictionary or list. Just use the search 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 order is important, you can always sort IEnumerable using the OrderByDescending or OrderByDescending extension methods.

Edit:

Take a look at the edited code example: If you want to order keys, just use the OrderBy method. In the same way, you can arrange words in alphabetical order using grouping.OrderBy(x => x) .

+8
source

A search is a set of mappings from a key to a collection of values. Using the key, you can get a set of related values:

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

Since it implements IEnumerable<IGrouping<TKey, TValue>> , you can use enumerated extension methods to convert it to the 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(); 
+4
source

All Articles