检查列表中的所有属性 [英] Check all properties in List

查看:102
本文介绍了检查列表中的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程列表为:-

 public class Requirement
    {
        public string Id { get; set; }
        public string desc { get; set; }
    }

列出lstRequirement

List lstRequirement

我在此列表中有3条ID和desc记录. 我想检查是否有任何项目不为空.

I have 3 records in this list for Id and desc. I wanted to check if any of item is not remaining null.

为此,我在下面使用了它:-

For that I used below :-

bool IsHavingValidTags = lstRequirement.All(_=> _.Id!=null && _.desc!=null);

此条件在上面的Linq上正常工作. 但我想将其设为通用.

This condition is working fine with above Linq. But I wanted to make it as Generic.

例如.将来可能会在Requirement类中添加5个以上的属性. 添加属性后,我还必须在Linq中进行更改.

Eg. In future there may get added 5 more properties in Requirement class. After addition of properties I also have to make changes in Linq.

如何使此Linq条件对所有属性通用? 我想检查列表中的任何属性是否不为空.

How can I make this Linq condition generic for all properties? I want to check any of the property is not remaining null in List.

请帮助.. !!!

我尝试了=>

 bool IsHavingValidTags = lstRequirement.All(_ => _ != null);

但没有给出期望的结果.

But not giving desired result.

推荐答案

您可以编写一个使用反射的扩展方法,如下所示:

You can write an extension method that uses reflection like the following:

public static class Extensions
{
    public static bool AreAllPropertiesNotNullForAllItems<T>(this IEnumerable<T> items)
    {
        var properties = typeof(T).GetProperties();
        return items.All(x => properties.All(p => p.GetValue(x) != null));
    }
}

然后这样使用:

bool IsHavingValidTags = lstRequirement.AreAllPropertiesNotNullForAllItems();

PropertyInfo.GetValue(object obj)方法重载.如果使用的是.NET Framework 4.0,则需要调用p.GetValue(x, null)

PropertyInfo.GetValue(object obj) method overload was introduced in .NET Framework 4.5. If you are using .NET Framework 4.0 you need to call p.GetValue(x, null)

这篇关于检查列表中的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆