查詢(xún)LINQ字符串方法淺析
LINQ字符串的查詢(xún)方式有很多,在這里介紹一種最常規(guī)的方法。如果大家有更多更好的方法,歡迎提出來(lái)一起討論。
LINQ可用于查詢(xún)和轉(zhuǎn)換LINQ字符串和字符串集合。它對(duì)文本文件中的半結(jié)構(gòu)化數(shù)據(jù)尤其有用。LINQ 查詢(xún)可與傳統(tǒng)的字符串函數(shù)和正則表達(dá)式結(jié)合使用。例如,可以使用 Split 或 Split 方法來(lái)創(chuàng)建字符串?dāng)?shù)組,然后可以使用LINQ 來(lái)查詢(xún)或修改此數(shù)組??梢栽?LINQ 查詢(xún)的where 子句中使用IsMatch 方法??梢允褂肔INQ 來(lái)查詢(xún)或修改由正則表達(dá)式返回的MatchCollection 結(jié)果。
LINQ查詢(xún)匹配給定的字符
- using System;
- using System.Linq;
- using System.Collections.Generic;
- using System.Collections;
- /// <summary>
- ///Class1 學(xué)習(xí)linq
- /// </summary>
- public class Class1
- {
- public Class1()
- {
- //
- //TODO: 在此處添加構(gòu)造函數(shù)邏輯
- //
- }
- 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";
- //將內(nèi)容拆分成數(shù)組
- string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
- //從數(shù)組里查詢(xún)符合條件的數(shù)據(jù)
- 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+",";
- //返回查詢(xún)后的結(jié)果
- return str+":::"+wordCount;
- }
- }
【編輯推薦】