其中先说明一下第二栏LAZY?的意思。我们知道有一个术语叫:Lazy Evalution。就是说不到用的时候程序不对它进行求值。
下面我们用个例子说明一下:
class Doctor
...{
public string Name;
public int Initials;
}
public static bool dump(Doctor d)
...{
System.Console.WriteLine(d.Initials);
return true;
}
Doctor[] doctors=...{new Doctor...{Name="Mary",Initials=123},
new Doctor...{Name="Jack",Initials=456},
new Doctor...{Name="Maggie",Initials=789}
};
var query = from d in doctors
where dump(d)
select d;
看看上面的代码会输出什么??答案是Nothing,什么都不输出。因为那个查询语句根本就没有执行。也就是说只有在下面用到query这个变量的时候,那个查询语句才真正的执行。大家可以在写完查询语句之后加上这样一句话
这样就会输出内容。这就是Lazy Evalution简单解释。用这种方法又好多好处。这里就不再具体介绍了。我们还可以看到并不是所有的LINQ函数都应用了Lazy Evalution。大家自己去尝试。
下面介绍几个比较重要的:
1 Any(下面继续用上面写的Doctor的例子)
//查询是否有一个名字叫Lary的医生,有返回true,没有返回false
bool inLakeForest = doctors.Any(doc => doc.Name == "Lary");
//等价于
var query = from doc in doctors
where doc.Name == "Lary"
select doc;
bool inLakeForest = query.Any();
2 Cast
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add("abc");
al.Add("def");
al.Add("ghi");
var strings = al.Cast<string>();
foreach(string s in strings) // "abc", "def", "ghi"
Console.WriteLine(s);
//Cast主要作用是让LINQ可以应用在非泛型集合上
3 Distinct
int[] ints = ...{ 1, 2, 2, 3, 2, 3, 4 };
var distinctInts = ints.Distinct();
foreach(var x in distinctInts) // 1, 2, 3, 4
Console.WriteLine(x);
//主要是返回一个集合中不同的元素
4 Except
int[] intsS1 = ...{ 1, 2, 2, 3, 2, 3, 4, 5, 6 };
int[] intsS2 = ...{ 1, 3, 6, 7 };
var diffInts = intsS1.Except(intsS2);
foreach(var x in diffInts) // 2, 4, 5
Console.WriteLine(x);
//可以查询在一个集合中出现却不能在另一个集合出现的元素
5 First
int[] ints = ...{ 1, 2, 3, 4, 5, 6 };
int first = ints.First();
Doctor doctor = doctors.First(doc => doc.Name == "Mary");
Console.WriteLine(first); // 1
Console.WriteLine(doctor.Initials); // 123
//返回集合中第一个满足条件的元素
6 OrderBy
int[] ints = ...{3, 1, 6, 4, 2, 5};
var sorted = ints.OrderBy(x => x);
foreach(var x in sorted) // 1, 2, 3, 4, 5, 6
Console.WriteLine(x);
//排序,还可以用OrderByDescending,逆序
7 Select
int[] ints = ...{1, 2, 3, 4, 5, 6};
var sameInts = ints.Select(x => x>=3);
foreach(var x in sameInts) // 3, 4, 5, 6
Console.WriteLine(x);
//选出满足条件的元素
8 Sum
int[] ints = ...{ 1, 2, 3, 4, 5, 6 };
decimal?[] values = ...{ 1, null, 2, null, 3, 4 };
int sum1 = ints.Sum();
decimal? sum2 = values.Sum();
Console.WriteLine(sum1); // 21
Console.WriteLine(sum2); // 10
//求和,可以应用在 int, int?, long, long?, decimal, decimal?, double, or double?. 这些类型上,返回值与上述类型一样
9 ToList
Doctors doctors = new Doctors();
var query = from doc in doctors
where doc.Name == "Mary"
select doc;
List<Doctor> chicago = query.ToList();
//把查询结果转换成List集合
10 Where
int[] ints = ...{1, 2, 3, 4, 5, 6};
var even = ints.Where( x => x % 2 == 0);
foreach(var x in even) // 2, 4, 6
Console.WriteLine(x);
//返回满足条件的元素集合