LINQ and strings (C#)
LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.Split or Regex.Split method to create an array of strings that you can then query or modify by using LINQ. You can use the Regex.IsMatch method in the
where clause of a LINQ query. And you can use LINQ to query or modify the MatchCollection results returned by a regular expression.
You can also use the techniques described in this section to transform semi-structured text data to XML. For more information, see How to: Generate XML from CSV Files.
The examples in this section fall into two categories:
Querying a block of text
You can query, analyze, and modify text blocks by splitting them into a queryable array of smaller strings by using the String.Split method or the Regex.Split method. You can split the source text into words, sentences, paragraphs, pages, or any other criteria, and then perform additional splits if they are required in your query.
How to: Count Occurrences of a Word in a String (LINQ) (C#)
Shows how to use LINQ for simple querying over text.
Shows how to split text files on arbitrary boundaries and how to perform queries against each part.
Demonstrates that a string is a queryable type.
Shows how to use regular expressions in LINQ queries for complex pattern matching on filtered query results.
Querying semi-structured data in text format
Many different types of text files consist of a series of lines, often with similar formatting, such as tab- or comma-delimited files or fixed-length lines. After you read such a text file into memory, you can use LINQ to query and/or modify the lines. LINQ queries also simplify the task of combining data from multiple sources.
Shows how to find all the strings that are present in one list but not the other.
Shows how to sort text lines based on any word or field.
Shows how to reorder fields in a line in a .csv file.
Shows how to combine string lists in various ways.
Shows how to create object collections by using multiple text files as data sources.
Shows how to combine strings in two lists into a single string by using a matching key.
Shows how to create new files by using a single file as a data source.
Shows how to perform mathematical computations on text data in .csv files.
Send feedback about: