[英]How to remove item from list which Id is not in list of Id's
我有一個看起來像這樣的表:
ID ProductId OrderId
-- --------- --------
1 1 1
2 2 1
3 4 1
4 2 2
5 6 2
6 7 2
首先,我得到所有具有相同OrderId的ProdictId
var listOfProdictids = db.OrderedProducts.Where(x => x.OrderId == 1).Select(x => x.ProductId).toArray();
我希望它看起來像1,2,4
我也有桌子產品
ID Brand Mark
-- --------- --------
1 Samsung Galaxy s10
2 Apple Iphone 7
3 Xiaomi Mi9
4 Huawei Honor
5 Sony Xperia
從數據庫中獲得ID為1、2、4的所有產品的最佳方法是什么? 我的想法:
List<ProductVM> products = db.Products.Select(x => x).toList();
獲取所有要列出的產品,並以某種方式刪除不在“ listOfProductids”數組中的Id 3和5。
要么
List<ProductVM> products = db.Products.Where(x => x.id == listOfProductids).Select(x => x).toList();
不確定lambda Where(x => x.id != listOfProdictids)
有效。 這個想法是將每個ProductId與數組中的Id進行比較。 如果匹配則選擇
知道怎么做嗎?
最終列表應如下所示:
ID Brand Mark
-- --------- --------
1 Samsung Galaxy s10
2 Apple Iphone 7
4 Huawei Honor
更新:基於答案npinti
如果要進行2個訂單,應該看起來像這樣嗎?
var orders = db.Orders.Select(x => x.ProductId).toArray();
to get Array with two orders 1 and 2
比
List<ProductVM> products = new List<ProductVM>();
foreach (ord o in orders)
{
// getting all product id's for first OrderId
HashSet<int> listOfProdictids = new HashSet<int>(db.OrderedProducts.Where(x => x.OrderId == o).Select(x => x.ProductId).toArray());
//getting list of products
var qwe = db.Products.Where(x => !listOfProducts.Contains(x.id)).Select(x => x).toList();
//Add list
products.Add(qwe)
}
return View (products);
要獲取訂單的所有商品ID
var listOfProdictids = db.OrderedProducts.Where(x => x.OrderId == 1).Select(x => x.ProductId).ToArray();
您需要減去訂購的所有產品。
List<ProductVM> removedProducts = db.Products.Where(c=>!listOfProdictids.Contains(c=>c.Id)).ToList();
並從“產品”表中刪除列表。
您可以嘗試執行以下操作: HashSet<int> listOfProdictids = new HashSet<int>(db.OrderedProducts.Where(x => x.Id == 1).Select(x => x.ProductId).toArray());
接着:
List<ProductVM> products = db.Products.Where(x => !listOfProducts.Contains(x.id)).Select(x => x).toList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.