简体   繁体   English

asp.net c# linq 根据来自另一个列表的 id 从模型生成列表

[英]asp.net c# linq generate list from model base on id from another list

My application is .net Core MVC.我的应用程序是 .net Core MVC。 I have two classes我有两节课

 public class Product
    {
        public int Id { get; set; }
        public string Buyer { get; set; }
        public int? ProductId  { get; set; }

        public ProductType ProductType { get; set; }
    }

public class ProductType
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }

        public ICollection<Product> Product { get; set; }
    }

I am trying to generate a list of product name using the following:我正在尝试使用以下内容生成产品名称列表:

List<ProductType> productnames;
var products = _context.Product().Where(x => x.Buyer == "Test" && x.ProductId != null).ToList();
foreach (var item in products)
{
productnames = _context.ProductType.Where(c => c.ProductId == item.ProductId).ToList(); 
}

Although I have 3 items in the list (products), I get just one item in productnames list.虽然我在列表中有 3 个项目(产品),但我在 productnames 列表中只有一个项目。

Note: I can't use Include because I am using another Core Web API to retrieve the data and can't use oData to return IQueryable object.注意:我不能使用 Include 因为我使用另一个 Core Web API 来检索数据并且不能使用 oData 来返回 IQueryable 对象。 So as a workaround I am using Sqlite for the client application, while the API is using MS Sql.因此,作为一种解决方法,我将 Sqlite 用于客户端应用程序,而 API 使用的是 MS Sql。

You only get one item (which will be the value from the last iteration) because you keep overwriting the value of productnames in each iteration.您只能获得一项(这将是上次迭代的值),因为您在每次迭代中都不断覆盖productnames的值。

You would need to add the result to the list.您需要将结果添加到列表中。 Assuming your .Where(c => c.ProductId == item.ProductId) returns only one record, then you could use .Single() , for example假设你的.Where(c => c.ProductId == item.ProductId)只返回一条记录,那么你可以使用.Single() ,例如

foreach (var item in products)
{
    productnames.Add(_context.ProductType.Single(c => c.ProductId == item.ProductId)); 
}

However you can simplify this by using a .Contains() statement但是,您可以使用.Contains()语句来简化此操作

// Select just the ProductId
var products = _context.Product
    .Where(x => x.Buyer == "Test" && x.ProductId != null)
    .Select(x => x.ProductId);
List<ProductType> productnames = _context.ProductType
    .Where(x => products.Contains(x.ProductId)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM