Manipulating strings with Linq

Code sample article
Table of Contents

Code examples for manipulating strings using Linq queries

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

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);

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))


// 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))

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);

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

var sb = new StringBuilder();
col.ToList().ForEach(item => sb.AppendFormat("{0}:", item));