public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double SaleTotal { get; set; }
}
public class Orders
{
public int ProductId { get; set; }
public double Total { get; set; }
}
List<Product> products = new List<Product>();
products.Add(new Product() { Id=1, Name="a1",SaleTotal=0 });
products.Add(new Product() { Id = 2, Name = "a2", SaleTotal = 0 });
products.Add(new Product() { Id = 3, Name = "a3", SaleTotal = 10 });
products.Add(new Product() { Id = 4, Name = "a4", SaleTotal = 20 });
products.Add(new Product() { Id = 5, Name = "a5", SaleTotal = 0 });
products.Add(new Product() { Id = 6, Name = "a6", SaleTotal = 30 });
products.Add(new Product() { Id = 7, Name = "a7", SaleTotal = 10 });
products.Add(new Product() { Id = 8, Name = "a8", SaleTotal = 50 });
products.Add(new Product() { Id = 9, Name = "a9", SaleTotal = 50 });
List<Orders> orders = new List<Orders>();
orders.Add(new Orders() { ProductId = 5, Total = 188 });
orders.Add(new Orders() { ProductId = 6, Total = 288 });
orders.Add(new Orders() { ProductId = 7, Total = 388 });
如何将这2个实体里的数据关联起来 最后返回 products 里的
//Id Name SaleTotal
//1 a1 0
//2 a2 0
//3 a3 10
//4 a4 20
//5 a5 188
//6 a6 288
//7 a7 388
//8 a8 50
//9 a9 50
------解决思路----------------------
var query = products.Select(p => new Product
{
Id = p.Id,
Name = p.Name,
SaleTotal = orders.Any(s => s.ProductId == p.Id) ? orders.First(s => s.ProductId == p.Id).Total : p.SaleTotal
});
------解决思路----------------------
var s = from m in products join n in ordrs on m.Id equals n.ProductId into temp from tt in temp.DefaultIfEmpty() select new {m.Id , m.Name ,total = tt==null?m.SaleTotal:tt.Total}