Manipulating strings with Linq

Code sample article
Table of Contents
Summary

Code examples for manipulating strings using Linq queries

Operations
Reverse string letters
How to do it
string input = "hello world";
string output = new string(input.ToCharArray().Reverse().ToArray());

Console.Write(output);
dlrow olleh
Reverse sentence words
How to do it
string input = "João is reversing this sentence";

string output = in.Split(' ')
			.Aggregate((accumulatedsentence, nextword) => nextword + " " + accumulatedsentence);

Console.Write(output);
sentence this reversing is João
Generate string
How to do it
 // Generate a string with length of 10 starting on character 'A'

string str = new string(Enumerable.Range(0, 10)
				  .Select(i => (char)('A' + i % 10))
		                  .ToArray());

Console.WriteLine(str);

// Generate a string with length of 10 starting on character 'A' and repeating 'ABC' pattern

str = new string(Enumerable.Range(0, 10)
                     .Select(i => (char)('A' + i % 3))
		     .ToArray());

Console.WriteLine(str);
ABCDEFGHIJ
ABCABCABCA
Filter characters that follow a condition implemented in a function

In the code sample filter characters that are digits

How to do it
string inputString = "ABCDE99F-J74-12-89A";

// Select only those characters that are numbers
IEnumerable<char> query = from ch in inputString
                          where Char.IsDigit(ch)
                          select ch;

foreach (char item in query)
         Console.Write(item + " ");
9 9 7 4 1 2 8 9
Count repeated words within a text
How to do it
string text = @"Historically, the world of data and the world of objects" +
         @" have not been well integrated. Programmers work in C# or Visual Basic" +
         @" and also in SQL or XQuery. On the one side are concepts such as classes," +
         @" objects, fields, inheritance, and .NET Framework APIs. On the other side" +
         @" are tables, columns, rows, nodes, and separate languages for dealing with" +
         @" them. Data types often require translation between the two worlds; there are" +
         @" different standard functions. Because the object world has no notion of query, a" +
         @" query can only be represented as a string without compile-time type checking or" +
         @" IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" +
         @" objects in memory is often tedious and error-prone.";

string searchitem = "data";

string[] words = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);

var query = from w in words
            where w.ToLowerInvariant() == searchitem.ToLowerInvariant()
            select w;

Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", query.Count(), searchitem);
3 occurrences(s) of the search term "data" were found.
Concatenate list of strings into a CSV string
How to do it
IEnumerable<string> col = new List<string> { "João", "Ana", "José" };

var csv = col.Aggregate((accumulatedsentence, nextword) => accumulatedsentence + "," + nextword);
Console.WriteLine(csv);

var csv1 = String.Join(":", col.ToArray());
Console.WriteLine(csv1);

var sb = new StringBuilder();
col.ToList().ForEach(item => sb.AppendFormat("{0}:", item));
Console.WriteLine(sb.ToString());
João,Ana,José
João:Ana:José
João:Ana:José: