Baklap4
Baklap4

Reputation: 4202

LINQ anonymous object select property if not null

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.

Upvotes: 1

Views: 3444

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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.

Upvotes: 3

Related Questions