LINQ and Strings
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 Split or Split method to create an array of strings that you can then query or modify by using LINQ. You can use the 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:
You can query, analyze, and modify text blocks by splitting them into a queryable array of smaller strings by using the Split method or the 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)
Shows how to use LINQ for simple querying over text.
- How to: Query for Sentences that Contain a Specified Set of Words (LINQ)
Shows how to split text files on arbitrary boundaries and how to perform queries against each part.
- How to: Query for Characters in a String (LINQ)
Demonstrates that a string is a queryable type.
- How to: Combine LINQ Queries with Regular Expressions
Shows how to use regular expressions in LINQ queries for complex pattern matching on filtered query results.
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.
- How to: Find the Set Difference Between Two Lists (LINQ)
Shows how to find all the strings that are present in one list but not the other.
- How to: Sort or Filter Text Data by Any Word or Field (LINQ)
Shows how to sort text lines based on any word or field.
- How to: Reorder the Fields of a Delimited File (LINQ)
Shows how to reorder fields in a line in a .csv file.
- How to: Combine and Compare String Collections (LINQ)
Shows how to combine string lists in various ways.
- How to: Populate Object Collections from Multiple Sources
Shows how to create object collections by using multiple text files as data sources.
- How to: Join Content from Dissimilar Files (LINQ)
Shows how to combine strings in two lists into a single string by using a matching key.
- How to: Split a File Into Many Files by Using Groups (LINQ)
Shows how to create new files by using a single file as a data source.
- How to: Compute Column Values in a CSV Text File (LINQ)
Shows how to perform mathematical computations on text data in .csv files.