C #: LINQ query to display all empty class properties

I have a class like this:

public class Test
{
    public string STR1{ get; set; }
    public INT INT1{ get; set; }
    public DOUBLE DBL1{ get; set; }
    public DATETIME DT1{ get; set; }
}

Usually, before saving the object, I will need to check all the properties inside this class and return a warning message if there is any empty / null property. There is an easy way to do this by simply checking each property as follows:

if (string.IsNullOrEmpty(t.STR1))
    return "STR1 is empty"
if (t.INT1 == 0)
    return "INT1 = 0";
if (t.DBL1 == 0)
    return "DBL1 = 0";
if (t.DT1 == DateTime.MinValue)
    return "DT1 is empty"

But what if my class has more properties, in fact it contains about 42 properties now and is still growing. So I was thinking of a “cleaner” way to do this check, and I found this topic that looks like my problem: Reflection (?) - Check if there is a property or field in the class that is empty or empty for each?

, , : null/empty string/0/DateTime.MinValue

, " ", LINQ ( #)

!

+4
1

, dynamic, .

.

private static IsEmpty(string s) { return string.IsNullOrEmpty(s); }
private static IsEmpty(double f) { return f == 0.0; }
private static IsEmpty(int i) { return i == 0; }
private static IsEmpty(DateTime d) { return d == DateTime.MinValue; }

:

List<string> emptyProperties = typeof(MyType).GetProperties()
    .Select(prop => new { Prop = prop, Val = prop.GetValue(obj, null) } )
    .Where(val => IsEmpty((dynamic)val.Val) // <<== The "magic" is here
    .Select(val => val.Prop.Name)
    .ToList();

dynamic, IsEmpty. , , , .

, catch-all, object, :

private static IsEmpty(object o) { return o == null; }
+7

Source: https://habr.com/ru/post/1546402/


All Articles