1

I'm looping through a list of companies and create an anonymous object by using the following linq query to retrieve the data i want to have.

The query is as following:

var customMail = this.db.Companies.Where(c => c.Id == company.Id)
                                     .Select(x => new { x.FromMail, x.FromName, x.Subject, x.EmailBody })

This object is filled correctly as a list with one result containing the correct details. But sometimes a field contains a null How would one filter out those null values?

I've tried the following without success:

var customMail = this.db.Companies.Where(c => c.Id == company.Id)
                                     .Select(x => new { x.FromMail, x.FromName, x.Subject, x.EmailBody })
                                     .Select(a => a.GetType().GetProperties()
                                                  .Where(pi => pi.GetValue(a) != null)
                                                  .Select(pi => pi.GetValue(a)));

I'd love to get the object without null values and then use its values within the method.

2
  • why you are using reflection? you can check each property in a Where Commented Feb 13, 2017 at 12:55
  • Since it's an annonymous object the props aren't available @EhsanSajjad Commented Feb 13, 2017 at 13:24

1 Answer 1

3

If you would like to filter out objects with any of its properties set to null, you can do it like this:

var customMail = this.db.Companies.Where(c => c.Id == company.Id)
    .Select(x => new { x.FromMail, x.FromName, x.Subject, x.EmailBody })
    .AsEnumerable() // Now you can use reflection
    .Where(
        a => a.GetType().GetProperties().All(pi => pi.GetValue(a) != null)
    );

This produces a list of anonymous objects with all properties set to non-null values.

Sign up to request clarification or add additional context in comments.

3 Comments

Or you can just check those properties manually before Select, there are just 4 of them after all.
@dasblinkenlight you don't need .AsEnumerable(), .Select() already returns one
The AsEnumerable was missing thanks! meanwhile i already fixed it without having to use reflection. I was thinking way off hahah. But nice it's doable!

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.