mercredi 27 septembre 2017

Return the values of an object's properties using lambda expression (C#)

My ultimate goal is to produce an array of strings (string[]) from a class and its properties, using a single lambda query and reflection.

The first code block successfully produces an IEnumerable, while the second one does not. The difference is that the second block attempts to filter out properties that have an empty value. The only thing that I can conclude is that my syntax in the second is off somehow.

Produces no Error:

var x = from p in GetType()
                 .GetProperties()
                 .Where(n => n.Name.Contains("mystring"))
        select p.GetValue(this));

Produces Error:

var x = from p in GetType()
                 .GetProperties()
                 .Where(n => n.Name.Contains("mystring") & 
                     !string.IsNullOrWhiteSpace(n.GetValue(this).ToString()))
        select p.GetValue(this));

How should I modify the second expression to filter out properties that have an null or empty value?





Aucun commentaire:

Enregistrer un commentaire