[英]How can I select from a collection with LINQ?
我有一個名為menuItems的IList集合。
這是我的MenuItem類:
public class MenuItem
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Order { get; set; }
}
當PartitionKey = "00"
和RowKey = "20"
時,如何從該集合中選擇訂單。 我可以為此使用LINQ嗎?
var result = menuItemsCollection
.Where(mnu=>mnu.RowKey=="20" && mnu.PartitionKey=="00")
.Select(mnu=>mnu.Order);
該查詢的結果將是IEnumerable<string>
,因為這就是Order
字段。
Where()
將集合向下過濾到所需的項目。 Select()
選擇“返回”的內容。 您可以選擇組成一個完全不同的對象,例如:
var result = menuItemsCollection
.Where(mnu=>mnu.RowKey=="20" && mnu.PartitionKey=="00")
.Select(mnu=>
new SomeOtherClass{Order=mnu.Order, RowKey=mnu.RowKey, RunOn=DateTime.Now});
使用System.Linq命名空間中的類,您可以執行以下操作:
var orders = menuItems
.Where(menuItem=>menuItem.PartitionKey=="00" && menuItem.RowKey=="20")
.Select(menuItem=> menuItem.Order)
是的,您必須使用“ System.Linq”,並且會為菜單項列表找到一組擴展名。
IList<MenuItem> list = ...
var orders = list.Where(item=>item.PartitionKey=="00" && item.RowKey=="20").Select(item => item.Order);
就像是:
var orders = from item in menuItems
where item.PartitionKey == "00" && item.RowKey == "20"
select new { Order = item.Order};
嘗試查看http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,以了解LINQ基礎知識。 這是一組非常清晰的例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.