Home > Back-end >  How to get property value from IEnumerable<object>
How to get property value from IEnumerable<object>

Time:08-11

I have a method which returns IEnumerable

public static IEnumerable<object> GetProps<T>(T obj)
    {        
        var result = obj.GetType().GetProperties()
            .Select(x => new { property = x.Name, value = x.GetValue(obj) })
            .Where(x => x.value == null)
            .ToList();
        return result;
    }

Above code will return result as [{"property":"YearOfBirth","value":null}]

I;m now trying to get property valueYearOfBirth from the returned result. Can someone please suggest/help ?

CodePudding user response:

The type of:

new { property = x.Name, value = x.GetValue(obj) }

is an anonymous type and you can't access fields or properties of that anonymous type outside of the function where it was defined, without using reflection. Here's how you would access its properties using reflection:

foreach (object prop in GetProps(obj))
{
    string propertyName = prop.GetType().GetProperty("property").GetValue(prop);
    object propertyValue = prop.GetType().GetProperty("value").GetValue(prop);
}

But that's not really the best solution. You don't care about the property value, since you're just returning ones where it's null. So a better solution is IEnumerable<string>:

public static IEnumerable<string> GetProps<T>(T obj)
{        
    var result = obj.GetType().GetProperties()
        .Select(x => new { property = x.Name, value = x.GetValue(obj) })
        .Where(x => x.value == null)
        .Select(x => x.property)
        .ToList();
    return result;
}

If you really want to return the property name with its value, I suggest using ValueTuple syntax instead of anonymous types, which will let you access the property and value fields of the ValueTuple (requires C# 7):

public static IEnumerable<(string property, object value)> GetProps<T>(T obj)
{        
    var result = obj.GetType().GetProperties()
        .Select(x => ( x.Name, x.GetValue(obj) ) })
        .Where(x => x.Item2 == null)
        .ToList();
    return result;
}

CodePudding user response:

var yearOfBirth = GetProps(someObject)
    .FirstOrDefault(x => x.property == "YearOfBirth")?.value;
    

Something like that.

You could alternatively just do:

dynamic someObjectDynamic = someObject;
var yearOfBirth = someObjectDynamic.YearOfBirth;
  • Related