您的位置:首页 > 其它

语言集成查询之Linq 入门

2010-01-14 11:21 453 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.Reflection;
namespace CSharp3StudyNote
{
/// <summary>
/// Ling To Objects 示例类
/// <para>1、Linq查询操作在数据源,查询本身及查询执行中是一个强类型的</para>
/// <para>2、查询中表达式中的类型必须与数据源中的元素的类型和foreach语句中迭代变量类型兼容</para>
/// <para>3、此强类型保证在编译时捕获类型异常,以便可以在用户遇到这些错误之前更正它们。</para>
/// <para>查询语法和方法语法</para>
/// <para>1、通过使用C#3.0中引入的声明性查询语法,介绍Linq文档中的多数查询都被编写成查询表达式,但是
/// .NET公共语言运行库(CLR)本身并不具有查询语句的概念。因此,在编译时查询表达式会转换在CLR确实了解的内容:方法调用。
/// 这些方法被称为“标准查询运算符”,他们具有以下名称:Where,Select,GroyupBy,Join,Max,Average。
/// </para>
/// <para>可以通过使用方法语法而非查询语法直接调用这些方法。</para>
/// </summary>
public class LinqToObjects
{

/// <summary>
/// 查询一个单词在一段文字中出现的次数.
/// </summary>
public void repeat()
{
string text = @"Burj Dubai, whose opening has been delayed twice since construction"+
@" began in 2004, will mark another milestone for the deeply indebted emirate with"+
@" a penchant for seeking new records.";
string searchWord = "will";
string [] source=text.Split(new char[]{' ','.',',','?',':'});
var matchQuery = from word in source
where word.ToLowerInvariant() == searchWord.ToLowerInvariant()
select word;
int wordCount = matchQuery.Count();
Console.WriteLine(searchWord+"在text中出现了:"+wordCount.ToString()+"次。");
}
/// <summary>
/// 调用扩展方法查询
/// </summary>
public void charTest()
{
string longString = "ABCDEF9923-2389J-ABCD1";
IEnumerable<char> stringQuery = from number in longString
where Char.IsDigit(number)
select number;
//Execute the query
foreach (char o in stringQuery)
Console.Write("longString字符串中包含以下:" + o + "数字;/n");
Console.WriteLine("共总:" + stringQuery.Count()+"个数。");
IEnumerable<char> sQuery = longString.TakeWhile(c => c != '-');
foreach (char c in sQuery)
Console.WriteLine("-前的字符串"+c);
}
/// <summary>
/// 应用查询表达式,查询文件目录
/// </summary>
public void QueryWithRegEx()
{
string startFolder = @"C:/Program Files/Microsoft Visual Studio 9.0/";//指定目录
IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);//获取该目录上的所有文件
//定义一个正规表达式
System.Text.RegularExpressions.Regex searchTerm = new System.Text.RegularExpressions.Regex(@"Visual (Basic|C#|C/+/+|J#|Studio|SoureSafe)");
//定义查询。
//1、首先找到出扩展名是htm的文件。
//2、然后把是htm文件的全名读取出来。
//3、使用扩展范围变量方法,来调用正规表达式对htm文件的内容进行匹配,
//4、如果存在符合条件的文件就查询出来
var QueryMachineFiles = from file in fileList
where file.Extension == ".htm"
let fileText = System.IO.File.ReadAllText(file.FullName)
let matches = searchTerm.Matches(fileText)
where searchTerm.Matches(fileText).Count > 0
select new
{
name = file.FullName,
matches = from System.Text.RegularExpressions.Match macth in matches
select macth.Value
};
Console.WriteLine("所匹配的文件名和文件:");
Console.WriteLine(searchTerm.ToString());
foreach (var v in QueryMachineFiles)
{
//string s = v.name.Substring(startFolder.Length - 1);
Console.WriteLine(v.name.ToString());
foreach (var v2 in v.matches)
{
Console.WriteLine(" " + v2.ToString());
}
}
}
/// <summary>
/// 使用Linq语方法查的垃圾文件
/// </summary>
public void QueryRubbish()
{
string startFolder = @"C:/";
Console.WriteLine("正在读取...");
TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks);//所有时间。
IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);
var RubbishFile = from file in fileList
where file.Extension == ".tmp"
let fileName = file.FullName
select fileName;
foreach (var v in RubbishFile)
Console.WriteLine(v.ToString());
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan tempTime = ts2.Subtract(ts1).Duration();
string timeSpan = tempTime.Hours.ToString() + "小时" + tempTime.Minutes.ToString() + "分钟" + tempTime.Seconds.ToString() + "秒"+tempTime.Milliseconds.ToString()+"毫秒";
Console.WriteLine("查询用时:" + timeSpan);
}
/// <summary>
///获取文件方法
/// </summary>
/// <param name="path">目录路径</param>
/// <returns>文件集合</returns>
public IEnumerable<System.IO.FileInfo> GetFiles(string path)
{
if (!System.IO.Directory.Exists(path))
throw new System.IO.DirectoryNotFoundException();
string[] fileNames = null;
List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();
fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
foreach (string name in fileNames)
files.Add(new System.IO.FileInfo(name));
//foreach (string name in System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories))
//    files.Add(new System.IO.FileInfo(name));

return files;
}
/// <summary>
/// Linq 和反射
/// <para>.NET Framework类库反射API可用于检查.NET程序集中的元数据,及创健位于该程序集中的类型,类型成员,参数等等集合</para>
/// <para>因为这些集合支持泛型IEnumerable接口,所以可以使用Linq查询他们</para>
/// </summary>
public void reflectionDemo()
{
string file = @"C:/Program Files/Microsoft Silverlight/3.0.40818.0/System.Core.dll";
Assembly assembly = Assembly.LoadFrom(file);
var pubTypeQuery = from type in assembly.GetTypes()
where type.IsPublic
from method in type.GetMethods()
where method.ReturnType.IsArray == true || (method.ReturnType.GetInterface(typeof(System.Collections.Generic.IEnumerable<>).FullName) != null && method.ReturnType.FullName != "System.String")
group method.ToString() by type.ToString();
foreach (var groupMethods in pubTypeQuery)
{
Console.WriteLine("Return type:" + groupMethods.Key.ToString());
foreach (var method in groupMethods)
{
Console.WriteLine(" " + method.ToString());
}
}
}

/// <summary>
/// LinqToArrayList Demo
/// <para>在使用Linq查询非泛型IEunmerable集合(ArrayList)时,必须显式声明范围变量的类型及反映此集合中对象的特定类型</para>
/// </summary>
public void LinqToArrayList()
{
//数据源
ArrayList alist = new ArrayList();
alist.Add(new Student { LastName = "LiLei", Score = new List<int> { 98, 93, 95 } });
alist.Add(new Student { LastName = "Lucy", Score = new List<int> { 100, 90, 85 } });
alist.Add(new Student { LastName = "LiLei", Score = new List<int> { 80, 70, 90 } });
alist.Add(new Student { LastName = "LiLei", Score = new List<int> { 75, 60, 78 } });
alist.Add(new Student { LastName = "LiLei", Score = new List<int> { 100, 120, 120 } });
//定义查询语句
var query = from Student student in alist //此处的范围变量显示的指定的强类型
where student.Score[0] > 85
select student;
Console.WriteLine("第一课成绩大于85的有:");
foreach (Student stu in query)
Console.WriteLine("Student Name:{0}----Score:{1}",stu.LastName,stu.Score[0]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: