C Sharper C Sharper - 1 year ago 94
C# Question

Check all properties in List

I have List of class as :-

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

List lstRequirement

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);

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

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.

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.

Please help..!!!

I tried With =>

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

But not giving desired result.

EDIT 1 :

enter image description here

Answer Source

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));

then use like this:

bool IsHavingValidTags = lstRequirement.AreAllPropertiesNotNullForAllItems();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download