我将尝试总结我的问题:
在我的产品表中,我有不同的产品,在 productPrice 表中,每种产品的价格都会随着时间而变化。
我正在尝试将结果放入如下类:
class ProductDictionary
{
public int ProductId { get; set; }
public IDictionary<int,double> YearValues { get; set; }
}
基本上:我需要类似的东西:(productId, Year, Value)
Product1,字典({2000, 10} {2001, 11},{2002, 13},{2003, 14},{2004, 15}} Product2,字典({2000, 9} {2001, 11},{2002, 18},{2003, 16},{2004, 17} }
我写了以下内容,但它没有给出我想要的
var result = (from x in products
join y in yearValuesForProduct2 on x.Id equals y.ProductId
select new ProductDictionary
{
ProductId = x.Id,
YearValues = (from z in yearValuesForProduct2
where z.ProductId == x.Id
select new { Year = z.Year, Value = z.Value })
.ToDictionary(k => k.Year, k => k.Value)
}).Distinct().ToList();
这返回:
Product1,字典({2000, 10} {2001, 11},{2002, 13},{2003, 14},{2004, 15}} Product1,字典({2000, 10} {2001, 11},{2002, 13},{2003, 14},{2004, 15}} Product1,字典({2000, 10} {2001, 11},{2002, 13},{2003, 14},{2004, 15}} Product1,字典({2000, 10} {2001, 11},{2002, 13},{2003, 14},{2004, 15}} Product1,字典({2000, 10} {2001, 11},{2002, 13},{2003, 14},{2004, 15}}
换句话说,重复的结果与连接的第二部分一样多。
任何帮助表示赞赏:
所有示例代码
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ProductYearValues
{
public int ProductId { get; set; }
public int Year { get; set; }
public double Value { get; set; }
}
public class ProductDictionary
{
public int ProductId { get; set; }
public string Name { get; set; }
public IDictionary<int, double> YearValues { get; set; }
}
static void Main(string[] args)
{
var newProduct1 = new Product() { Id = 1, Name = "Product 1" };
var newProduct2 = new Product() { Id = 2, Name = "Product 2" };
var newProduct3 = new Product() { Id = 3, Name = "Product3" };
List<Product> products = new List<Product>() { newProduct1 };
List<ProductYearValues> yearValuesForProduct2 = new List<ProductYearValues>()
{
new ProductYearValues() {ProductId =newProduct2.Id, Year = 2005, Value = 20},
new ProductYearValues() {ProductId =newProduct2.Id, Year = 2006, Value = 22},
new ProductYearValues() {ProductId =newProduct2.Id, Year = 2007, Value = 22},
new ProductYearValues() {ProductId =newProduct2.Id, Year = 2009, Value = 23},
new ProductYearValues() {ProductId =newProduct2.Id, Year = 2010, Value = 24},
new ProductYearValues() {ProductId =newProduct2.Id, Year = 2011, Value = 25}
};
var result = (from x in products
join y in yearValuesForProduct2 on x.Id equals y.ProductId
select new ProductDictionary
{
ProductId = x.Id,
Name = x.Name,
YearValues = (from z in yearValuesForProduct2
where z.ProductId == x.Id
select new { Year = z.Year, Value = z.Value })
.ToDictionary(k => k.Year, k => k.Value)
}).Distinct().ToList();
}