I have a dictionary that stores strings as keys and ints as values that represent words and the number of times they occur. The user needs to be able to sort them by number of uses or alphabetically by 1st letter. I’d prefer to use LINQ although I am rather new to it. I have been able to group the words based on starting letter using the following code:
public string AlphabeticWordBuilder()
{
List<String> words = this.myWords.WordsAsList();
words.Sort();
return GroupWords(words);
}
private static string GroupWords(List<String> words)
{
String formatedWords = string.Empty;
var groups =
from w in words
group w by w.First();
foreach (var group in groups)
{
formatedWords += ("\n" + group.Key + ":\n");
foreach (var w in group)
{
formatedWords += (w);
}
}
return formatedWords;
}
However this method requires me to convert the keys of my dictionary into a list causing me to lose my values. I should be able to group my dictionary by the value in a similar fashion but I do not know how to incorporate the key/value relationship into the code I am using for the alphabetic sorting. Can someone please post an example of using LINQ to group a dictionary by value?
Also I’d like to avoid the LINQ method syntax and continue to use the LINQ query expression syntax shown above if possible.
Example output alphabetically:
Words starting with a:
and adventure a an (ect.)
Example output by frequency:
Words occurring 1 time(s):
stuff and problems
An incomplete example of what I’m trying to do:
public string FrecquincyWordBuilder()
{
string fromatedWords = string.Empty;
var groups =
from w in this.myWords
group w by w.value;
}
This is the code I am using.