我正在遍历公司列表并使用以下linq查询创建一个匿名对象来检索我想要的数据。
查询如下:
var customMail = this.db.Companies.Where(c => c.Id == company.Id)
.Select(x => new { x.FromMail, x.FromName, x.Subject, x.EmailBody })
此对象作为列表正确填充,其中一个结果包含正确的详细信息。但有时一个字段包含null
如何过滤掉那些空值?
我尝试了以下但没有成功:
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)));
我希望获得没有空值的对象,然后在方法中使用它的值。
答案 0 :(得分:2)
如果您要过滤掉任何属性设置为null
的对象,您可以这样做:
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)
);
这将生成一个匿名对象列表,其中所有属性都设置为非空值。