zoukankan      html  css  js  c++  java
  • Linq中的Select与Select many

    Select与Select Many

    之前在项目中查询数据库中的数据,都是通过sql语句来查询的,但是随着时代的发展,微软在.Net Framework 4.5版中推出的一个主要的特性——LINQ。

    LINQ是Language Integrate Query的缩写,意为语言集成查询。其中有两种查询方式,分为语句查询和方法查询。

    语句查询:from a in Table

                  select  a ;

    方法查询:Table.select(x=>x)

    今天要讲的是方法查询中的Select与Select Many。

    select:将序列中的每个元素投影到新表中(官方定义)。个人理解:就是查询什么得到什么,比如查询表的所有元素,那么就得到表里的所有元素,不对得到的元素作出修改(Table.select(x=>x))。

    select many:将序列的每个元素投影到一个 System.Collections.Generic.IEnumerable`1,并将结果序列组合为一个序列。

    参考:https://www.cnblogs.com/zhangyuanbo12358/p/4107882.html 例子1:select

    1 string[] text = { "Today is 2018-06-06", "weather is sunny", "I am happy" };
    2 
    3             var tokens = text.Select(s => s.Split(' '));
    4             foreach (string[] line in tokens)
    5 
    6                 foreach (string token in line)
    7 
    8                     Console.Write("{0}.", token);
    9             Console.ReadKey();

    结果:

    select many:

    1 string[] text1 = { "Today is 2018-06-06", "weather is sunny", "I am happy" };
    2             var tokens1 = text1.SelectMany(s => s.Split(' '));
    3             foreach (string token in tokens1)
    4             Console.Write("{0}.", token);            
    5             Console.ReadKey();

    结果和上图一样。结论:在select中,首先对字符串“Today is 2018-06-06”按照“ ”进行切割,变成字符串数组{“Today”,“is”," 2018-06-06"},但是select many则是在此基础上,对得到的序列进行重组,即将数组中的元素进行合并,变成字符串“Todayis2018-06-06”,

    这就是两者的区别。

    当然最重要的还是什么时候用select ,什么时候用select many呢?

         如果你是仅仅查询表中的某个列(属性)的,并对其使用聚合函数(sum,count,avg),那么select适合你  StudentTable.select(x=>x.age>=20).count()——查询学生表中年龄大于20的人数

        如果你查询表中的某个集合,但是你又想对集合里的对象进行聚合,那么select many适合你 SchoolTable.SelectMany(x => x.StudentCollection).Where(y => y.age >=20).count()——查询学校表里中的学生表中年龄大于20的人数,

    X:school类里的StudentCollection属性,该属性类型是集合,集合里存放的是student对象。Y:student对象

    以上就是本人对select 与select many的见解,如果有什么不对的地方,欢迎指正,谢谢

     

     

  • 相关阅读:
    能大大提升工作效率和时间效率的9个重要习惯
    hibernate的校验
    8. semahpore原理
    chklist
    android textview 自动换行 整齐排版
    fiddler接口测试,js代码修改日志展示(埋点用)
    Python模块之 tqdm进度条
    Python抓取网页到本地
    Python模块之 clint 进度条
    python windows下pip安装错误whl文件安装错误
  • 原文地址:https://www.cnblogs.com/sjitLearn/p/9144306.html
Copyright © 2011-2022 走看看