【问题标题】:asp.net c# linq generate list from model base on id from another listasp.net c# linq 根据来自另一个列表的 id 从模型生成列表
【发布时间】:2017-10-18 06:37:32
【问题描述】:

我的应用程序是 .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.

【问题讨论】:

  • @StephenMuecke,谢谢。效果很好。
  • 所以用绿色勾号检查他的答案

标签: c# asp.net asp.net-mvc linq


【解决方案1】:

您只会得到一个项目(这将是上次迭代的值),因为您在每次迭代中不断覆盖 productnames 的值。

您需要将结果添加到列表中。假设您的.Where(c =&gt; 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 2015-11-28
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多