Search code examples
c#iterationanonymous-typesenumerable

Get Values from IEnumerable<anonymousType>


I've got code to get DisplayNameAttribute from PropertyInfo and return it as a Pair

{Propertyname = "", DisplayName = ""}
public static IEnumerable GetDisplayNames<T>() => typeof(T).GetProperties()
                  .Where(p => p.IsDefined(typeof(DisplayNameAttribute), false))
                  .Select(p => new
                  {
                      PropertyName = p.Name,
                      DisplayName = p.GetCustomAttributes(typeof(DisplayNameAttribute),
                              false).Cast<DisplayNameAttribute>().Single().DisplayName
                  });

It would be fine, but I guess I don't understand anonymous types too well and I was wondering how to return value for specific item (if it is even possible - though it has to).

I thought it works like Dictionary<Tkey, TValue>, but now I know it is not. To simplify question:

How can I iterate through such construction?


Solution

  • Or could it be your are looking for a dictionary like:

    public static Dictionary<string, string> GetDisplayNames<T>() =>
        typeof(T).GetProperties()
            .Where(p => p.IsDefined(typeof(DisplayNameAttribute), false))
            .ToDictionary(
                p => p.Name, // Key
                p.GetCustomAttributes(typeof(DisplayNameAttribute), false) 
                 .Cast<DisplayNameAttribute>()         
                 [0] // Linq not really required
                 .DisplayName); // Value