Linq to return 基于对象中另一个值的值

Linq to return a value based on another value in an object

我有一个这样的对象:

{
  "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 查询 return 具有特定名称的订单的 '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 中执行此操作?

我认为这应该可以。

  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);
 

您应该同时使用 WhereSelect - 第一个用于过滤您需要的值,第二个用于投影您想要 return 的属性:

 orders
    .orderSummaries
    .Where(x => x.Name == request.name)
    .Select(x => x.orderTypeId);

您需要使用.Where() instead of .Select() to filter out the list and then .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(): Filters a sequence of values based on a predicate.

在你的例子中,谓词是 x.Name == request.name

Select(): Projects each element of a sequence into a new form.

在您的情况下,新表单是 orderTypeId(s) 的 IEnumerable 而不是 orderSummaries.

的整个 IEnumerable