I have a class like this
public class Product
{
public int Id {get;set;}
public string Name {get;set;}
public Category Category {get;set;}
}
Now I want to query a List with Linq
var result = from p in products
select p;
What I want to achive is that the result will set a default Category if it is empty.
What I can do is this
var result = from p in products
select new Product()
{
Id = p.Id,
Name = p.Name,
Category = p.Category ?? new Category()
}
but that requires me to set every field again. But that is not what I want because my real world entity has about 50 properties not 3 and I also have to renember to edit the code If I add another property in the future. What I am thinking is something more like this:
var result = from p in products
select p { Category = p.Category ?? new Category() };
but that does not compile.
like I would do while constructing a product:
var product = new Product() { Category = new Category() };
I know I could just do this:
foreach (var p in result)
{
if(p.Category == null)
p.Category = new Category();
}
but I am passing the result to the caller an I don't want to itterate through my products at this moment.
select new Product...approach and reassign every property. With the disadvantage that I have to modify the code everytime I add another property to my class. This is dangerous. I will never store the result, and even if I would try, my model has a[MinLength(5)]dataannotation on category.name, so it would fail anyway.