问题描述
我需要循环访问数据库中的自定义对象类型的属性,并仅显示包含数据的列。
这意味着我不能简单地将对象列表绑定到数据网格。
我不想遍历每个对象,看看列是否为空/空,并确定在UI中显示它。
我在发送对象之前在我的业务层中想到的是,我只发送一个IEnumerable,只显示那些应该可见的列。因此,我正在考虑使用Linq to Object来做到这一点,但我不确定这会非常漂亮。
有谁知道我可以使用的解决方案没有大量的IF语句,我可以通过一个大对象(30列左右)来确定应该显示或不显示的内容。
Foreach(客户中的CustomerData客户数据)
{
if(!customerdata.address.Equals())
{
dgvCustomerData.Column [Address ] .visible = false;
}
//继续检查其他数据列...
}
我希望在用户界面和所有IF中避免所有这些...
我对这个有一个大脑放屁能帮助我吗?
感谢
请看。您可以使用反射来获取所有对象的属性,并循环查看它们是否为null。然后,您可以返回Key =属性名称和Value = true / false的KeyValuePair对象集合。然后,您可以使用键值对来设置列的可见性......
I need to loop through the properties of a custom object type that I'm getting back from the database and only show the columns that contain data.This means I cannot simply bind the list of objects to the datagrid.I don't want to loop through each object and see if the column is empty/null and determine in the UI to display it.What I'm thinking is in my business layer before I send the object back I would send an IEnumerable back with only those columns that should be visible. Thus I was thinking of using Linq to Object to do this, but I'm not sure that would be very pretty.
Does anyone know of a solution that I could use without a ton of IF statements that I could do to check through a large object (30 or so columns) to determine what should be shown or not.
Foreach (CustomerData customerdata in Customers)
{
if (!customerdata.address.Equals(""))
{
dgvCustomerData.Column["Address"].visible = false;
}
//Continue checking other data columns...
}
I wish to avoid all of this in the UI and all the IFs...I'm having a brain fart on this one can anyone help me?
Thanks
Take a look at the .NET Reflection Libraries. You can use reflection to get ahold of all of an object's properties, and loop through them to find out if they are null or not. Then you could return a collection of KeyValuePair objects where Key = property name, and Value = true/false. You'd then use the keyvaluepairs to set column visibility...
这篇关于C#匿名类型foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!