简体   繁体   中英

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

My application is .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.

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. So as a workaround I am using Sqlite for the client application, while the API is using 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.

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

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

// 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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