我必须根据自定义属性从对象集合创建动态对象。
public class Customer
{
[AccountAttribute(name: "CustomerAccountID")]
public int CustomerID { get; set; }
[RoleAttribute(name: "RoleUserID")]
[AccountAttribute(name: "AccountRole")]
public int RoleID { get; set; }
}
我有客户数据列表
var custData= GetCustomerData();
我想根据属性筛选客户集合。
如果我基于帐户属性进行筛选,则我期望客户ID和角色ID的列表,并且在新创建的列表中属性名称应为CustomerAccountID,AccountRole。
如果基于角色属性进行筛选,则只有角色 ID 是必需的,字段名称应为 RoleUserID。
上面的类只是一个示例,有 20 多个字段可用,并且具有三个不同的属性。
有些字段属于单个属性,但有些字段属于多个属性。
当您在编译时不知道属性名称时,创建动态对象的最佳方法是ExpandoObject
- 它允许您使用IDictionary<string, object>
接口访问对象,因此您需要做的就是添加适当的键值对:
private static dynamic CustomerToCustomObject<TAttribute>(Customer customer)
where TAttribute : BaseAttribute // assuming the Name property is on a base class for all attributes
{
dynamic result = new ExpandoObject();
var dictionary = (IDictionary<string, object>)result;
var propertiesToInclude = typeof(Customer).GetProperties()
.Where(property => property.GetCustomAttributes(typeof(TAttribute), false).Any());
foreach (var property in propertiesToInclude)
{
var attribute = (BaseAttribute)(property.GetCustomAttributes(typeof(TAttribute), false).Single());
dictionary.Add(attribute.Name, property.GetValue(customer));
}
return result;
}