I have an object as such:
{
"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"
}
]}
I am trying to use a linq query to return the 'orderTypeId' of the order that has a particular name.. but i can't go further
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
Not sure how to do this in linq?
You should be using both Where
and Select
- the first is for filtering the values you need, and the second is for projecting the properties you want to return:
orders
.orderSummaries
.Where(x => x.Name == request.name)
.Select(x => x.orderTypeId);
I believe this should do.
var orderTypeId = orders
.orderSummaries
.FirstOrDefault(x => x.Name == request.name)?
.orderTypeId;
if you're sure the Name
is unique. otherwise:
var orderTypeIds = orders
.orderSummaries
.Where(x => x.Name == request.name)
.Select(x => x.orderTypeId);
You need to use .Where()
instead of .Select()
to filter out the list and then .Select()
to project only 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()
: Filters a sequence of values based on a predicate.
In your case, predicate is x.Name == request.name
Select()
: Projects each element of a sequence into a new form.
In your case, new form is IEnumerable of orderTypeId
(s) instead of entire entire IEnumerable of orderSummaries
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.