LinQ中的基本查询操作和SQL中的功能是一样的,对于其异同点,我们来了解了解:
1)Select
语法:
<span style="font-family:SimHei;font-size:18px;"> public static IEnumerable<TResult> Select<TSource,TResult>( this IEnumerable<TSource>source,Func<TSource,TResult>selector)</span>说明:
2)Where
语法:
<span style="font-family:SimHei;font-size:18px;">public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource>source,Func<TSource,bool>predicate)</span>
3)举例:
首先我们来写一个扩展类,为IEnumerablet<string>提供输出的方法
<span style="font-family:SimHei;font-size:18px;"> //扩展类,只要是静态就可以
public static class ExtraClass
{
//为IEnumerablet<string>提供输出的方法
public static void Print(this IEnumerable<string> ie)
{
//获取可遍历的接口
IEnumerator<string> result = ie.GetEnumerator();
Console.WriteLine("\n-------------------------------------\n");
while (result.MoveNext())
{
Console.WriteLine(result.Current);
}
Console.WriteLine("\n---------------------------------------\n");
}
}</span>写一个泛型集合,为其存放几条数据:<span style="font-family:SimHei;font-size:18px;"> private void BtnSelect_Click(object sender, EventArgs e)
{
//LinQ to Objects
//泛型集合数据persons
List<string> persons = new List<string>();
persons.Add("li si");
persons.Add("meng meng");
persons.Add("huo huo");
persons.Add("niu nan");
persons.Add("hu hu");
persons.Add("tu zi");
persons.Add("huo er");
persons.Add("huo xu");</span>这样我们就可以根据选择来显示输出结果:
1、输出person中所有元素:
<span style="font-family:SimHei;font-size:18px;"> //输出person中所有的元素 var result=persons.Select(p => p);</span>
显示结果:
2、输出person中姓huo的(以下三种语句都显示同样的效果)
<span style="font-family:SimHei;font-size:18px;"> //输出person中姓huo的(以下三种语句都必答同样的效果)
//var result=persons.Where(p=>p.StartsWith("huo"));
//var result = persons.Select(p=>p).Where(p => p.StartsWith("huo"));
//var result = persons.Where(p => p.StartsWith("huo")).Select(p=>p);</span>显示的效果:
当然,也可以直接使用Where,利用bool委托参数来执行,
<span style="font-family:SimHei;font-size:18px;"> var result=persons.Where(p=>Judge(p));
result.Print();
}
public bool Judge(string s)
{
if (s.StartsWith("huo"))
{
return true;
}
else
{
return false;
}
}</span>显示效果一样,但是却直接显示了Where()语句的用法举得例子也只是一些常用的查询语句,其他的在继续学习中!
原文:http://blog.csdn.net/huo065000/article/details/43926369