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

  • 相关阅读:
    jsp初识
    OAuth2.0
    微服务参考案例
    3.0技术架构落地
    聚合层改进意见-彭泉锋-2018.10.31
    图片分步加载(解决图片load函数刷新不加载问题)
    IOS iframe宽高问题(来至stackoverflow)
    jquery easy-ui 分页插件的运用(给td添加事件,获取汇总内容)
    JS 获取当前日期(yy-mm-dd HH-MM-SS)
    JQ iframe 子元素找父级 的元素
  • 原文地址:https://www.cnblogs.com/kfx2007/p/2693676.html
Copyright © 2020-2023  润新知