A dictionary where value is an anonymous type in C#

前端 未结 5 536
鱼传尺愫
鱼传尺愫 2020-12-01 04:26

Is it possible in C# to create a System.Collections.Generic.Dictionary where TKey is unconditioned class and TValue

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 05:00

    I think ASP.NET MVC didn't exit at the time this question was made. It does convert anonymous objects to dictionaries internally.

    Just take a look at the HtmlHelper class, for example. The method that translates objects to dictionaries is the AnonymousObjectToHtmlAttributes. It it's specifc to MVC and returns an RouteValueDictionary, however.

    If you want something more generic, try this:

    public static IDictionary AnonymousObjectToDictionary(object obj)
    {
        return TypeDescriptor.GetProperties(obj)
            .OfType()
            .ToDictionary(
                prop => prop.Name,
                prop => prop.GetValue(obj)
            );
    }
    

    One intersting advatages of this implementation is that it returns an empty dictionary for null objects.

    And here's one generic version:

    public static IDictionary AnonymousObjectToDictionary(
        object obj, Func valueSelect
    )
    {
        return TypeDescriptor.GetProperties(obj)
            .OfType()
            .ToDictionary(
                prop => prop.Name,
                prop => valueSelect(prop.GetValue(obj))
            );
    }
    

提交回复
热议问题