Edit 2 :
This is probably the easiest way to implement it . I tested it, it works fine. You can create an infinite number of lines.
public IEnumerable<string> GenerateStrings() { foreach(string character in Alphabet()) { yield return character; } foreach (string prefix in GenerateStrings()) { foreach(string suffix in Alphabet()) { yield return prefix + suffix; } } } public IEnumerable<string> Alphabet() { for(int i = 0; i < 26; i++) { yield return ((char)('A' + i)).ToString(); } }
Material I wrote earlier:
You can also write a small recursive function that returns any string with a specific index. This may not be optimal in performance because there are several duplicate sections, but it may be fast enough for your purpose.
This is pretty short and easy:
string GetString(int index) { if (index < 26) { return ((char)('A' + index)).ToString(); } return GetString(index / 26 - 1) + GetString(index % 26); }
(can also be placed in another method:
List<string> strings = Enumerable.Range(0, 1000) .Select(x => GetString(x)) .ToList();
This is working code, just wrote a test for it.
Edit: for example, the application "full linq way" from GetString:
public void IEnumerale<string> GenerateStrings() { int index = 0; // generate "infinit" number of values ... while (true) { // ignoring index == int.MaxValue yield return GetString(index++); } } List<string> strings = GenerateStrings().Take(1000).ToList();
Stefan steinegger
source share