我正在传递一个带有System.DataTable
的视图,并从中渲染html table
。列的可见性随每个login
而变化。
(即)考虑有5列为colA
、colB
、colC
、colD
、colE
,并且这些列的可见性随每次登录而变化。有些登录只有colA
,有些有colA
和colD
,有些有全部。
以下是适用于上述要求的的实现
sql procedure
将返回所有这些列,每个列都有一个bit
字段列,以便在这样的视图中显示/隐藏该列。
colA
、isColA
、colB
、isColB
等
过滤controller
中的实际恒星
DataTable dt = "Method here that will generate datatable";
var cols = new string[] { "colA", "isColA", "colB", "isColB", "colC", "isColC" and so on };
var colsRemove = new List<string> { };
for(int i=0; i < cols.Length; i +=2)
{
colsRemove.Add(dt.Columns[cols[i + 1]].ToString());
if(!dt.Rows[0][cols[i + 1]].Equals(true))
{
colsRemove.Add(dt.Columns[cols[i]].ToString());
colsRemove.Add(dt.Columns[cols[i + 1]].ToString());
}
}
var newDt = new DataTable();
newDt = dt.Clone();
foreach(var item in colsRemove)
{
newDt.Columns.Remove(item);
}
foreach (DataRow row in dt.Rows)
{
newDt.ImportRow(row);
}
这很好,这是我的实际问题,
- 实施是否是一种标准做法
- 有没有其他最简单的方法来实现这一要求
我无法判断这是否是一种标准做法,但我会使用DynamicObject。这是一篇关于DynamicObect的博客文章,它也值得一读关于ExpandoObject的文章。http://blogs.msdn.com/b/csharpfaq/archive/2009/10/19/dynamic-in-c-4-0-creating-wrappers-with-dynamicobject.aspx
以下是LinqPad的片段
void Main()
{
List<dynamic> flexibleList = new List<dynamic>();
dynamic aa = new FlexibleTable();
aa.ColumnA = "testA";
aa.ColumnB="testB";
flexibleList.Add(aa);
aa = new FlexibleTable();
aa.ColumnA = "testA1";
aa.ColumnB="testB1";
flexibleList.Add(aa);
foreach(dynamic item in flexibleList){
foreach(var columnName in item.VisibleColumns){
new object[]{item[columnName]}.Dump();
}
}
}
// Define other methods and classes here
public class FlexibleTable: DynamicObject{
private Dictionary<string,object> Columns{get; set;}
public FlexibleTable(){
this.Columns = new Dictionary<string,object>();
}
public override bool TryGetMember(GetMemberBinder binder, out object result){
if(Columns.ContainsKey(binder.Name)){
result = Columns[binder.Name];
return true;
}else{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value){
Columns[binder.Name] = value;
return true;
}
public override bool TryGetIndex(
GetIndexBinder binder, object[] indexes, out object result)
{
string index = (string)indexes[0];
return Columns.TryGetValue(index , out result);
}
public IEnumerable<string> VisibleColumns{
get{ return Columns.Select(x=>x.Key);}
}
}