I am randomly generating a list of Sales objects:
public class Sale
{
public string Name { get; set; }
public List<Product> Products { get; set; }
public decimal Value
{
get { return Products.Sum(p => p.Price); }
}
}
public class Product
{
public decimal Price { get; set; }
}
Using this setup:
private void SetProducts()
{
var seed = (int)(DateTime.UtcNow.Ticks | 0x0000FFFF);
var random = new Random(seed);
Products = new List<Product>();
for(var i = 0; i < 100; i++)
{
Products.Add(new Product
{
Price = random.Next(500, 1500)
});
}
}
private void SetSales()
{
Sales = new List<Sale>();
for(var i = 0; i < 100; i++)
{
Sales.Add(new Sale{
Name = "Sale #" + i,
Products = GetProducts()
}
}
}
private List<Product> GetProducts()
{
var seed = (int) (DateTime.UtcNow.Ticks | 0x0000FFFF);
var random = new Random(seed);
var max = random.Next(1, 7);
var products = new List<Product>();
for(var i = 0; i < max; i++)
{
products.Add(Products[random.Next(Products.Count)];
}
return products;
}
public Dashboard()
{
SetProducts();
SetSales();
}
When I evaluate these sales values, they all have the exact same value. When I walk through the debugger and evaluate them, the evaluated sales have the correct value, but all of the sales whose evaluation waited until this object was passed down to the View (this is part of a mock MVC dashboard) all of the data is identical. This makes me believe that the Products
field is being computed lazily, but how can I fix this? I was under the impression that this might be an issue if I were using a different Enumerable, but I was of the opinion that a List<T>
would not have this problem.
EDIT: I also want to mention that even if the products field is being computed lazily, I have a hard time believe that all of that computation is being done within the same tick. A tick should be around 100ns and while I know C# is a very efficient language, I have a hard time believing it could do all of that in less than 100ns.