zoukankan      html  css  js  c++  java
  • LINQ 学习笔记 Kevin

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

  • 相关阅读:
    java 枚举类小结 Enum
    hibernate查询
    java装饰者模式理解
    内部类学习
    java使用json将HashMap转化成javabean小例子
    HashMap存储数据赋值javabean简单示例
    java数组转化成集合
    java正则匹配并提取字串
    Windows cmd命令反斜杠问题
    自动化构建工具
  • 原文地址:https://www.cnblogs.com/kfx2007/p/2693676.html
Copyright © 2011-2022 走看看