[英]Lambda expression question
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
var query =
fruits.Select((fruit, index) =>
new { index, str = fruit.Substring(0, index) });
foreach (var obj in query)
{
Console.WriteLine("{0}", obj);
}
/*
This code produces the following output:
{index=0, str=}
{index=1, str=b}
{index=2, str=ma}
{index=3, str=ora}
{index=4, str=pass}
{index=5, str=grape}
*/
有人可以解釋一下,“索引”在這里如何與元素的數組索引關聯?
說,我需要一個查詢,而不是首字母返回整個對象(在這種情況下為字符串)+相關索引的查詢。
index
變量只是一個計數器,它在遍歷fruits
列表時從0開始遞增。 在這個例子中之間存在着某種天然的聯系index
的位置和fruit
中fruits
,你是通過迭代fruits
一個元素在同一時間。
對於您有關訪問“整個對象”的問題,我不確定。 您已經可以訪問此:
var query = fruits.Select((fruit, index) => new { index, fruit });
fruit
是指當您遍歷fruits
的當前元素時。
要在每種情況下返回整個字符串,只需修改查詢即可:
var query =
fruits.Select((fruit, index) =>
new { index, str = fruit });
index
就是數組元素的索引。
不太確定您要問什么,請嘗試:
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
var query =
fruits.Select((fruit, index) =>
new { index, str = fruit });
foreach (var obj in query)
{
Console.WriteLine("{0}", obj);
}
在Select的重載中使用Index來描述您的lambda當前正在迭代的對象的索引。
這就是Select
特定重載的工作方式: “函數的第二個參數代表源元素的索引” 。
如果您想要整個字符串,則可以執行以下操作:
var query = fruits.Select((fruit, index) => new { index, str = fruit });
lambda表達式將第一個變量名稱填充為項本身,第二個變量填充為索引。
因此,如果您擁有(fruit,index)
則:
fruit =數據對象。
index =數組中的索引。
關於第一個問題,它是Select
的重載。 請參閱: http : //msdn.microsoft.com/en-us/library/bb534869.aspx
也許分解一下此表達式的作用將有助於您理解它:
fruits.Select((fruit, index) =>
new { index, str = fruit.Substring(0, index) });
Select(...)
=使用輸入,如所示返回輸出。
(fruit, index)
=將選定的水果分配給可變fruit
,並將索引(在Enumerable中的位置(fruit, index)
分配給index
。 如前所述,這只是您可以使用的一個重載(選項)。 如果您不在乎索引值,只需將其忽略即可。
=>
=返回以下值
new { ... }
=創建一個匿名類型的實例。 此類型將具有兩個屬性: index
和str
。 index
的值將是變量index
。 str
的值將是水果上子字符串的結果。
因此,如果您只想要水果,則可以這樣重寫它:
fruits.Select(fruit => fruit);
如果您仍然想要索引,並帶有水果的全名:
fruits.Select((fruit, index) =>
new { index, str = fruit});
Select對於返回與輸入內容不同的信息集很有用。
通過使用稍微復雜一些的場景作為示例:
例如,如果您有類似的類:
public class Customer {
public int Id {get; set;}
public string Name { get; set;}
public List<Order> Orders { get; set;}
}
public class Order {
public int Id { get;set;}
public double TotalOrderValue { get;set}
}
您可以使用簡單的Select語句返回客戶,以及該客戶訂購的總金額:
var customersTotalSpend = customers.Select(
customer =>
new {
customer,
TotalSpend = customer.Orders.Select(order => order.TotalOrderValue).Sum()
});
然后,如果需要的話,我們可以使用TotalSpend值來做一些事情,例如獲取10個最大的支出者:
var biggestCustomers = customersTotalSpend.OrderByDescending(customerSpend=> customer.TotalSpend).Take(10);
現在有意義嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.