2011-11-17 74 views
2

我有一组属性,如下所示。如何根据C#中的输入值抑制列表项目?

class CustomerInfo 
{ 
    public string Address { get; set; } 
    public string FirstName{ get; set; } 
    public string LastName{ get; set; } 
    public string PostCode{ get; set; } 
    public string Title{ get; set; } 
    public string Email{ get; set; } 
} 

我有一个方法叫getinfo(string Fields)内搭串字段名像下面,基于参数“名字,姓氏,标题”参数字段我的方法应该

<CustomerInfo> 
<FirstName></FirstName> 
<LastName></LastName> 
<Title></Title> 
</CustomerInfo> 

如何只返回列表我可以在c#中执行此操作吗?

Public List<CustomerInfo> getinfo(string Fields) 
{ 
List<CustomerInfo> list = new List<CustomerInfo>(); 
……. 
return list; 
} 

请做必要的事。

+0

有些困难(如果你想以可维护的方式来做)。如果它是可维护的,则为 – Oliver

+0

。那么它很好。 – user995099

+0

+1,为好问题。 –

回答

2

你可以像这样做反射。我没有试图编译这个,但它应该非常接近。

List<CustomerInfo> inList = new List<CustomerInfo>(); 
List<CustomerInfo> outList = new List<CustomerInfo>(); 

string[] properties = string.split(','); 
foreach(var info in inList) 
{ 
    CustomerInfo filteredInfo = new CustomerInfo(); 
    foreach(var property in properties) 
    { 
     var pi = typeof(CustomerInfo).GetProperty(property); 
     pi.SetValue(filteredInfo, pi.GetValue(info, null), null); 
    } 
    outList.Add(filteredInfo); 
} 

return outList; 
+0

的属性名称此解决方案非常感谢您的工作 – user995099

相关问题