查詢LINQ字符串方法淺析
作者:佚名
本文介紹了一種查詢LINQ字符串的方法,LINQ 可用于查詢和轉換LINQ字符串和字符串集合。之后可以使用 LINQ 來查詢或修改由正則表達式返回的 MatchCollection 結果。
LINQ字符串的查詢方式有很多,在這里介紹一種最常規的方法。如果大家有更多更好的方法,歡迎提出來一起討論。
LINQ可用于查詢和轉換LINQ字符串和字符串集合。它對文本文件中的半結構化數據尤其有用。LINQ 查詢可與傳統的字符串函數和正則表達式結合使用。例如,可以使用 Split 或 Split 方法來創建字符串數組,然后可以使用LINQ 來查詢或修改此數組。可以在 LINQ 查詢的where 子句中使用IsMatch 方法??梢允褂肔INQ 來查詢或修改由正則表達式返回的MatchCollection 結果。
LINQ查詢匹配給定的字符
- using System;
- using System.Linq;
- using System.Collections.Generic;
- using System.Collections;
- /// <summary>
- ///Class1 學習linq
- /// </summary>
- public class Class1
- {
- public Class1()
- {
- //
- //TODO: 在此處添加構造函數邏輯
- //
- }
- public string LinqToString()
- {
- 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 searchTerm = "data";
- //將內容拆分成數組
- string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
- //從數組里查詢符合條件的數據
- var matchQuery = from s in source where s.IndexOf('a')==0 orderby s ascending select s ;
- int wordCount = matchQuery.Count();
- string str="";
- foreach(string a in matchQuery)
- str+=a+",";
- //返回查詢后的結果
- return str+":::"+wordCount;
- }
- }
【編輯推薦】
責任編輯:林琳
來源:
博客園