[英]C# asp.net create string list from a another list which returns list of class objects
[英]asp.net c# linq generate list from model base on id from another list
我的应用程序是 .net Core MVC。 我有两节课
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; }
}
我正在尝试使用以下内容生成产品名称列表:
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();
}
虽然我在列表中有 3 个项目(产品),但我在 productnames 列表中只有一个项目。
注意:我不能使用 Include 因为我使用另一个 Core Web API 来检索数据并且不能使用 oData 来返回 IQueryable 对象。 因此,作为一种解决方法,我将 Sqlite 用于客户端应用程序,而 API 使用的是 MS Sql。
您只能获得一项(这将是上次迭代的值),因为您在每次迭代中都不断覆盖productnames
的值。
您需要将结果添加到列表中。 假设你的.Where(c => c.ProductId == item.ProductId)
只返回一条记录,那么你可以使用.Single()
,例如
foreach (var item in products)
{
productnames.Add(_context.ProductType.Single(c => c.ProductId == item.ProductId));
}
但是,您可以使用.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.