Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection (?) - Check for null or empty for each property/field in a class?

Tags:

I have a simple class as such:

public class FilterParams {     public string MeetingId { get; set; }     public int? ClientId { get; set; }     public string CustNum { get; set; }     public int AttendedAsFavor { get; set; }     public int Rating { get; set; }     public string Comments { get; set; }     public int Delete { get; set; } } 

How do I check for each of the property in the class, if they are not null (int) or empty/null (for string), then I'll convert and add that property's value to a List<string>?

Thanks.

like image 975
Saxman Avatar asked Aug 02 '11 17:08

Saxman


1 Answers

You can use LINQ to do that:

List<string> values     = typeof(FilterParams).GetProperties()                           .Select(prop => prop.GetValue(yourObject, null))                           .Where(val => val != null)                           .Select(val => val.ToString())                           .Where(str => str.Length > 0)                           .ToList(); 
like image 50
Frédéric Hamidi Avatar answered Oct 02 '22 18:10

Frédéric Hamidi