gpt4 book ai didi

c# - 获取列表中每个项目的对象集合(产品)

转载 作者:行者123 更新时间:2023-12-03 22:55:54 28 4
gpt4 key购买 nike

我有 orders 集合,其中包含 products 集合。我将一些产品 ID 作为列表传递给该方法。我需要返回与任何匹配的产品列表input 列表中的 id。

我需要像这样使用 foreach 循环吗?请指教..

   public List < ProductOrderData > ListProductsByOrderId(List < Guid > input) {
List < ProductOrderData > products = new List < ProductOrderData > ();
foreach(var id in input) {
var orders = this.Collection.AsQueryable().SelectMany(order => order.Products.Where(product => product.Id == id));
}

}

更新: enter image description here

更新2: enter image description here

更新 3:我传递了产品 ID,我需要从与产品 ID 匹配的订单中获取产品列表。

最佳答案

I have orders collection that contains products collection.

好的,所以你有这样的东西:

var ordersWithTheirProducts = ...
.Select(... => new Order
{
// some Order properties:
Id = ...
OrderDate = ...
ClientId = ...

// Products of this Order:
Products = ...
.Select( product => new Product
{
// Several Product properties
Id = product.Id,
Name = product.Name,
Price = product.Price,
...
},
};

I'm passing some product ids as list

IEnumerable<Guid> productIds = ...

I need to return a list of products matching with any of the id in the input list.

因此,您想要选择在您的任何订单中使用的所有产品,并且如果该产品的 ID 是 ProductIds 中的值之一,那么您希望它出现在结果中。

首先我们提取您的订单中使用的所有产品,然后我们删除重复项,最后我们只保留那些在您的产品 ID 中有一个 ID 的产品:

var result = Orders.SelectMany(order => order.Products)  // extract all Products
.Distinct() // remove duplicate products
.Where(product => productIds.Contains(product.Id))
// keep only those products with an Id that is in productIds

关于c# - 获取列表中每个项目的对象集合(产品),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60055097/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com