C # anonymous type foreach looping

I need to skip the properties of the custom object type that I am returning from the database and show only the columns containing the data. This means that I cannot just bind a list of objects to a datagrid. I do not want to iterate over each object and see if the / null column is empty and determine its display in the user interface. What I think is in my business layer, before sending the object back, I would send IEnumerable back with only those columns that should be visible. So I was thinking about using Linq for Object for this, but I'm not sure if it will be very beautiful.

Does anyone know of a solution that I could use without a ton of IF statements that I could do to check a large object (about 30 columns) to determine what should be displayed or not.

Foreach (CustomerData customerdata in Customers) { if (!customerdata.address.Equals("")) { dgvCustomerData.Column["Address"].visible = false; } //Continue checking other data columns... } 

I want to avoid all this in the user interface and all IFs ... I have a brain fart on this, can anyone help me?

thanks

+1
source share
2 answers

Check out the .NET Reflection libraries . You can use reflection to get all the properties of an object and scroll through them to see if they are zero or not. Then you can return a collection of KeyValuePair objects, where Key = property name, and Value = true / false. Then you should use keyvaluepairs to determine the visibility of the column ...

+1
source

You can do the following to simplify it a bit

 Action<T,string> del = (value,name) => { if ( value.Equals("") ) { dgvCustomerData.Column[name].Visible = false; } }; foreach ( var data in Customers ) { del(data.address,"Address"); del(data.name, "Name"); ... } 
+4
source

All Articles