Loading

LINQ 学习笔记

1.LINQ只能用来查询数据吗?

Answer:NO,LINQ还可以用来对数据进行转换。例如把一个intl类型的数组转换成string类型,传统的方法可能需要写一个新的方法,循环遍历该数组中的每一个值,逐一进行转换。而LINQ就可以方便高效地转换。

 

2.Var关键字的使用

当变量的类型只有在编译的时候才能确定的情况下,我们可以使用var关键字来代替我们不明确的变量类型。

 

3.Cast 或 OfType 方法的用法

LINQ只能应用在实现了IEnumberalbe<T>接口的对象中,对于传统C#集合类型,可以使用Cast(OfType)方法对对象进行转换。

example:

ArrayList arrayList = new ArrayList();
arrayList.Add("Adams");
arrayList.Add("Arthur");
arrayList.Add("Buchanan");
IEnumerable<string> names = arrayList.Cast<string>().Where(n => n.Length < 7);
foreach(string name in names)
Console.WriteLine(name);

or:

ArrayList arrayList = new ArrayList();
arrayList.Add("Adams");
arrayList.Add("Arthur");
arrayList.Add("Buchanan");
IEnumerable<string> names = arrayList.OfType<string>().Where(n => n.Length < 7);
foreach(string name in names)
Console.WriteLine(name);

 

PS:Cast方法和OfType方法的区别:1.Cast方法会试图将集合中每一个元素都转换成目标类型,一旦有一个转换失败,该方法就会抛出异常。2.OfType方法则只对该集合中能够进行转换的元素进行转换。

 

4.Not Bug-Free

LINQ查询通常会延迟查询,并非如你所想的那样执行。

Example:

string[] strings = { "one", "two", null, "three" };
Console.WriteLine("Before Where() is called.");
IEnumerable<string> ieStrings = strings.Where(s => s.Length == 3);
Console.WriteLine("After Where() is called.");
foreach(string s in ieStrings)
{
Console.WriteLine("Processing " + s);
}

Result:

Before Where() is called.
After Where() is called.
Processing one
Processing two
Unhandled Exception: System.NullReferenceException: Object reference not set to an
instance of an object.

---------------------

这就是说,LINQ查询并非在代码所在的位置就立即执行,而是延迟到循环遍历的时候才开始执行。这样的好处是可以获取最新的数据。

posted @ 2012-09-19 14:48  青岛欧姆网络科技  阅读(211)  评论(0编辑  收藏  举报