CSharp · Console
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Reflection;
using System.Linq;
public class Program
{
public static void Main()
{
var myList = new List<MyCustomClass>{
new MyCustomClass {Id=1, Name="Name1", Value="Value1"},
new MyCustomClass {Id=2, Name="Name2", Value="Value2"},
new MyCustomClass {Id=3, Name="Name3", Value="Value3"},
new MyCustomClass {Id=4, Name="Name4", Value="Value4"}
};
var customData = myList.Select(x=> ToDynamicDisplayName(x));
Console.WriteLine("Hello World");
foreach(var item in customData){
item.Dump();
}
}
public static object ToDynamicDisplayName(object input)
{
var type = input.GetType();
dynamic dObject = new ExpandoObject();
var dDict = (IDictionary<string, object>)dObject;
foreach (var p in type.GetProperties())
{
var prop = type.GetProperty(p.Name);
var displayNameAttr = p.GetCustomAttribute<DisplayNameAttribute>(false);
if (prop == null || prop.GetIndexParameters().Length != 0) continue;
if (displayNameAttr != null)
{
dDict[displayNameAttr.DisplayName] = prop.GetValue(input, null);
}
else
dDict[p.Name] = prop.GetValue(input, null);
}
return dObject;
}
}
public class MyCustomClass {
public int Id {get;set;}
[DisplayName("Custom Name")]
public string Name {get; set;}
[DisplayName("Custom Value")]
public string Value {get; set;}
}