C# anonymous type foreach looping

浪子不回头ぞ 提交于 2019-12-13 00:27:19

问题


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


回答1:


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...




回答2:


You could 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");
  ...
}


来源:https://stackoverflow.com/questions/1882935/c-sharp-anonymous-type-foreach-looping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!