2

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.

3
  • 1
    Why aren't the properties initialized in the first place? If a product should have at least a category initialized with the default constructor, initialize the backing field accordingly. Commented May 24, 2013 at 10:33
  • If you're working with an ORM as datasource this may cause new Categories to be inadvertently inserted into the database. Commented May 24, 2013 at 13:32
  • That won't happen. Currently I am using the 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. Commented May 28, 2013 at 12:05

1 Answer 1

2

I wouldn't recommend doing this in Linq. You're mixing business logic ( null values should be default initialized) with DataAcess code (get me products).

Can you not change your product class itself. Modify the "Category" property to something like.

private Category _category

public Category Category 
{
    get 
    {
        if (_category == null)
            _category = new Category();

        return _category;
    }
    set
    {
        _category = value;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.