zoukankan      html  css  js  c++  java
  • lambda select和where区别

    本文用一个linq to xml语法作为示例,以下是用来操作的xml:
    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <!--This is a comment.Just input what you want to say.-->
    <UsersInfomation>
      <User ID="1">
        <Name>Alex</Name>
        <Hometown>HRB</Hometown>
        <Age>22</Age>
      </User>
      <User ID="2">
        <Name>Fu</Name>
        <Hometown>SY</Hometown>
        <Age>27</Age>
      </User>
      <User ID="3">
        <Name>Abe</Name>
        <Hometown>HRB</Hometown>
        <Age>24</Age>
      </User>
    </UsersInfomation>

    在一个输出台控制程序中加载xml,并调用方法:
    XElement xd = XElement.Load(@"D:1userInfomation.xml");
    GetHometown(xd);
    Console.WriteLine();


    //统计hometown为HRB的人数
    private static void GetHometown(XElement xe)
    {
        //Select用于选择输出(不能作为筛选条件),比如:.Select(s=>s)将输出一个实体;.Select(s=>s.Value)将输出值;
        //而下面的代码将输出的是bool类型:
        var hometown = xe.Descendants("Hometown").Select(s => s.Value == "HRB");
        //输出为:


    //可以看出,输出的行数是全部行,只是输出的内容是bool,这是由Select子句决定的。

     
        //Where扩展方法才是用来进行条件筛选(虽然它返回的也是bool值,但作用和Select不一样)
        //等同于:var hometown = xe.Descendants("Hometown").Where(s => s.Value == "HRB").Select(s => s);
        var hometown = xe.Descendants("Hometown").Where(s => s.Value == "HRB");
        //输出为:


    //可以看出,输出了符合条件的行。

        //查询语法(等同于上一句)
        //var hometown = from h in xe.Descendants("Hometown")
        //               where h.Value == "HRB"
        //               select h;

        int count = 0;
        foreach (var h in hometown)
        {
            Console.WriteLine(h);
            count++;
        }
        Console.WriteLine("==============>"+count);
    }

    ------------------------------ Select用法续 《Pro ASP.NET MVC 3 Framework》p529---------------------
    作用:
    1、用来过滤要显示的字段
    2、定义字段要显示的样式
    如:
    var formattedData=data.Select(m=>new { ClientName=m.ClientName,Date=m.Date.ToShortDateString()});

  • 相关阅读:
    HttpMessageNotWritableException: Could not write JSON: No serializer found for class ****
    处理【Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operatio】
    java 日历类Calendar用法
    linux配置nginx
    linux 重命名文件和文件夹
    CentOS 6.7 配置 yum 安装 Nginx
    maven打包时跳过单元测试
    Eclipse 保存文件时自动格式化代码
    mybatis大于号,小于号,去地址符,单引号,双引号转义说明
    玩转Eclipse — 自动代码生成的Java Code Template
  • 原文地址:https://www.cnblogs.com/zhaow/p/9754621.html
Copyright © 2011-2022 走看看