[LINQ] Select 投影語句

  • 21169
  • 0
  • LINQ
  • 2016-05-08

[LINQ] Select 投影語句

有關Select 投影語句可參考以下:

image

 

在此仍延用上篇的假資料類別,http://www.dotblogs.com.tw/yc421206/archive/2013/03/16/96854.aspx

select new 可將查詢到的資料投影成另外一個類別

image

 

沒有用select new 關鍵字查詢到的資料仍是原本的型態

image

 

查詢符合條件的內容及索引

法一:使用 let 關鍵字

            where customer.City == "台北"
            let Index = this._customerList.IndexOf(customer)
            select new { customer, Index };

foreach (var customer in query)
{
    Console.WriteLine("Index : " + customer.Index);
}

result:
Index : 0
Index : 2
 
法二:
    .Where(c => c.City == "台北")
    .Select(c => new { custom = c, Index = this._customerList.IndexOf(c) });

foreach (var customer in query)
{
    Console.WriteLine("Index : " + customer.Index);
}

result:
Index : 0
Index : 2

 

將查詢後的索引帶出來:
   .Where(c => c.City == "台北")
   .Select((c, Index) => new { c, Index });

foreach (var customer in query)
{
    Console.WriteLine("Index : " + customer.Index);
}

result:
Index : 0
Index : 1

 

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo