Reputation: 967
I have an object with many properties. I create a list of these objects and weed out the bad ones by finding cases where an important property is null or empty. Like...
theList.RemoveAll(p => string.IsNullOrEmpty(p.ID));
How can I do a similar check but instead of checking a single property, check if any property in the object IsNullOrEmpty?
I've been working with Reflection to get things like
object x = typeof(MyObject).GetProperties().
Select(p => p.GetValue(exampleObject, null)).
Where(v => string.IsNullOrEmpty(v.ToString())));
but I don't grock it well enough to put it all together. Please set me straight.
Upvotes: 2
Views: 3444
Reputation: 236218
Thus it makes sense to apply String.IsNullOrEmpty
only to string values, you should select only properties of string type:
List<MyObject> objects = new List<MyObject>();
// fill list
var stringProperties = typeof(MyObject)
.GetProperties()
.Where(p => p.PropertyType == typeof(string))
.ToArray();
And then get filtered sequence of objects:
var query = objects.Where(o =>
stringProperties.All(p => !String.IsNullOrEmpty((string)p.GetValue(o))));
You can use same approach to remove objects from list:
objects.RemoveAll(o =>
stringProperties.Any(p => String.IsNullOrEmpty((string)p.GetValue(o))));
Upvotes: 2
Reputation: 116118
check if any property in the object IsNullOrEmpty?
theList.RemoveAll(x => x.GetType().GetProperties()
.Select(p => p.GetValue(x, null))
.Any(p => p == null));
Upvotes: 5