[英]How to RemoveAll from list where any object property is null or empty?
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.
我创建了这些对象的列表,并通过查找重要属性为null或为空的情况来清除不良对象。 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? 如何进行类似的检查,而不是检查单个属性,而是检查对象IsNullOrEmpty中是否有任何属性?
I've been working with Reflection to get things like 我一直在与Reflection合作,以获取诸如
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.
请让我挺直。
check if any property in the object IsNullOrEmpty?
检查对象IsNullOrEmpty中是否有任何属性?
theList.RemoveAll(x => x.GetType().GetProperties()
.Select(p => p.GetValue(x, null))
.Any(p => p == null));
Thus it makes sense to apply String.IsNullOrEmpty
only to string values, you should select only properties of string type: 因此,仅将
String.IsNullOrEmpty
应用于字符串值是有意义的,您应该仅选择字符串类型的属性:
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))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.