I have a string of words separated by spaces. How to split the string into lists of words based on the words length?
Example
inpu
First, let's declare a class that can hold a length as well as a list of words
public class WordList
{
public int WordLength { get; set; }
public List Words { get; set; }
}
Now, we can build a list of word lists with
string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc ";
string[] words = input.Trim().Split();
List list = words
.GroupBy(w => w.Length)
.OrderBy(group => group.Key)
.Select(group => new WordList {
WordLength = group.Key,
Words = group.Distinct().OrderBy(s => s).ToList()
})
.ToList();
The lists are sorted by length and aphabetically respectively.
Result

e.g.
list[2].WordLength ==> 4
list[2].Words[1] ==> "bbbb"
If you want, you can process the result immediately, instead of putting it into a data structure
string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc ";
var query = input
.Trim()
.Split()
.GroupBy(w => w.Length)
.OrderBy(group => group.Key);
// Process the result here
foreach (var group in query) {
// group.Key ==> length of words
foreach (string word in group.Distinct().OrderBy(w => w)) {
...
}
}