Edit: I am glad that my original answer helped the OP solve their problem. However, having thought a little over the problem, I adapted it (and strongly recommend it against my previous solution, which I left at the end of the message).
Simple approach
string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc cccc bbb bb aa "; var words = input.Trim().Split().Distinct(); var lookup = words.ToLookup(word => word.Length);
Description
First, we crop the entrance to avoid empty elements from external spaces. Then we split the string into an array. If there are several spaces between words, you need to use StringSplitOptions , as in Mark the answer .
After calling Distinct only include each word once, we convert words from IEnumerable<string> to Lookup<int, string> , where the length of the words is represented by the key (int) , and the words themselves are stored in the value (string) .
Wait, how is this possible? Don't we have a few words for each key? Of course, but exactly what the Lookup class exists for:
Lookup<TKey, TElement> is a collection of keys, each of which maps to one or more values. A Lookup<TKey, TElement> resembles a Dictionary<TKey, TValue> . The difference is that the Dictionary matches keys to single values, while the search matches keys to collections of values.
You can instantiate Lookup by calling ToLookup on an object that implements IEnumerable<T> .
Note
There is no public constructor to create a new instance of Lookup. Furthermore, Lookup objects are immutable, that is, you cannot add or remove elements or keys from a search after it has been created.
word => word.Length is a word => word.Length key element: it determines that we want to index (or group, if you want) Lookup by the length of words.
Using
Enter all words in the console
(similar to the requested query)
foreach (var grouping in lookup) { Console.WriteLine("{0}: {1}", grouping.Key, string.Join(", ", grouping)); }
Exit
2: aa, bb, cc 3: aaa, bbb, ccc 4: aaaa, bbbb, cccc
Put all words of a certain length in a List
List<String> list3 = lookup[3].ToList();
Key Order
(note that they will return an IOrderedEnumerable<T> , so access to the key is no longer possible)
var orderedAscending = lookup.OrderBy(grouping => grouping.Key); var orderedDescending = lookup.OrderByDescending(grouping => grouping.Key);
Original answer - please do not do this (poor performance, code mess):
string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc cccc bbb bb aa "; Dictionary<int, string[]> results = new Dictionary<int, string[]>(); var grouped = input.Trim().Split().Distinct().GroupBy(s => s.Length) .OrderBy(g => g.Key);