lambda select和where區別

來源:互聯網
上載者:User

標籤:欄位   his   技術分享   private   分享圖片   inpu   coding   encoding   分享   

本文用一個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:\1\userInfomation.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()});

lambda select和where區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.