C# 匿名类型 foreach 循环
我需要循环遍历从数据库返回的自定义对象类型的属性,并且仅显示包含数据的列。 这意味着我不能简单地将对象列表绑定到数据网格。 我不想循环遍历每个对象并查看该列是否为空/空并确定在 UI 中显示它。 我的想法是在我的业务层中,在将对象发送回之前,我会发送一个 IEnumerable ,其中仅包含那些应该可见的列。因此,我正在考虑使用 Linq to Object 来执行此操作,但我不确定这是否会非常漂亮。
有谁知道我可以使用一个解决方案,而无需使用大量 IF 语句来检查大型对象(大约 30 列)以确定应该显示或不显示的内容。
Foreach (CustomerData customerdata in Customers)
{
if (!customerdata.address.Equals(""))
{
dgvCustomerData.Column["Address"].visible = false;
}
//Continue checking other data columns...
}
我希望避免 UI 和所有 IF 中的所有这些...... 我在这件事上脑子里放屁了,有人能帮助我吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作来简化一点
You could do the following to simplify it a bit
查看.NET 反射库 。您可以使用反射来获取对象的所有属性,并循环遍历它们以查明它们是否为空。然后,您可以返回 KeyValuePair 对象的集合,其中 Key = 属性名称,Value = true/false。然后,您可以使用键值对来设置列可见性......
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...