LINQ 和字符串
LINQ 可用于查询和转换字符串和字符串集合。它对文本文件中的半结构化数据尤其有用。LINQ 查询可与传统的字符串函数和正则表达式结合使用。例如,可以使用 Split 或 Split 方法来创建字符串数组,然后可以使用 LINQ 来查询或修改此数组。可以在 LINQ 查询的 where 子句中使用 IsMatch 方法。可以使用 LINQ 来查询或修改由正则表达式返回的 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;
}
}

浙公网安备 33010602011771号