我有一個這樣的物件:
{
"orderSummaries": [
{
"orderTypeId": "8b3206ed-0ea0-41bc-8d4b-b39882f81019",
"name": "DefaultOrder",
"description": "default order"
},
{
"orderTypeId": "6ebc76dd-1d0f-4292-84f2-f95b71f821cb",
"name": "Loan purchase",
"description": "loan purchase order"
}
]}
我正在嘗試使用 linq 查詢來回傳具有特定名稱的訂單的“orderTypeId”.. 但我無法更進一步
e.g orders.orderSummaries.Select(x => x.Name == request.name)//this will be Loan purchase
// return the order orderTypeId value with the name of the request variable
不確定如何在 linq 中執行此操作?
uj5u.com熱心網友回復:
您應該同時使用Where和Select- 第一個用于過濾您需要的值,第二個用于投影您想要回傳的屬性:
orders
.orderSummaries
.Where(x => x.Name == request.name)
.Select(x => x.orderTypeId);
uj5u.com熱心網友回復:
您需要使用.Where()而不是.Select()過濾掉串列,然后.Select()僅投影orderTypeId
var result = orders.orderSummaries
.Where(x => x.Name == request.name) //Filter orderSummaries based on request.name
.Select(x => x.orderTypeId); //Project only orderTypeId instead of entire orderSummary object
Where():根據謂詞過濾一系列值。
在您的情況下,謂詞是 x.Name == request.name
Select():將序列的每個元素投影到新的形式中。
在您的情況下,新形式是 IEnumerable of orderTypeId(s) 而不是整個 IEnumerable of orderSummaries。
uj5u.com熱心網友回復:
我相信應該這樣做。
var orderTypeId = orders
.orderSummaries
.FirstOrDefault(x => x.Name == request.name)?
.orderTypeId;
如果你確定Name是獨一無二的。否則:
var orderTypeIds = orders
.orderSummaries
.Where(x => x.Name == request.name)
.Select(x => x.orderTypeId);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/408617.html
標籤:
上一篇:如何在selenium中查找元素(By.XPATH)和發送密鑰?
下一篇:在每個第n個元素上創建字串陣列
