目前我有一个列表,我会遍历它,如果满足条件,我会清除数据(请参阅foreach)。
当前代码但不是我想要的,我想使用强类型
public class ViewCommonItemVM
{
public string Name { get; set; }
public List<string> Data { get; set; }
public string Bullet { get; set; }
public ViewCommonItemVM()
{
Data = new List<string>();
}
}
List<ViewCommonItemVM> commons = new List<ViewCommonItemVM>();
commons.Add( new ViewCommonItemVM { Name = "Projects", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Companies", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Schools", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Hobbies", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Locations", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Interests", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Stuff", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Things", Data = someListHere });
commons.Add( new ViewCommonItemVM { Name = "Somelist", Data = someListHere });
foreach (var common in commons.Where(c => c.Data.Count != 0))
{
count++;
if (count > 4 && common.Data.Count != 0)
common.Data.Clear();
}
但我希望从stronly类型中受益,所以
想要
对象
public class ViewCommonVm
{
public ViewCommonItemVM Projects {get;set;}
public ViewCommonItemVM Companies {get;set;}
public ViewCommonItemVM Schools {get;set;}
public ViewCommonItemVM Hobbies {get;set;}
public ViewCommonItemVM Locations {get;set;}
public ViewCommonItemVM Interests {get;set;}
public ViewCommonItemVM Stuff {get;set;}
public ViewCommonItemVM Things {get;set;}
public ViewCommonItemVM Somelist {get;set;}
}
public class ViewCommonItemVM
{
public string Name { get; set; }
public List<string> Data { get; set; }
public string Bullet { get; set; }
}
// Here it should iterated trough the object, and after
// 4 lenght properties != 0, clear the property list
我怎样才能做到这一点?
答案 0 :(得分:0)
你能用linq来解决这个问题吗?
这样的事可能有效
commons.Where(x => x.Data.Any()).Skip(4).ToList().ForEach(x => x.Data = new List<string>());
答案 1 :(得分:0)
必须使用反射:
void MyClear()
{
int count = 0;
foreach (System.Reflection.PropertyInfo item in typeof(ViewCommonVm).GetProperties())
{
ViewCommonItemVM common = (ViewCommonItemVM)item.GetValue(this);
if (common.Data.Count() != 0)
{
count++;
if (count > 4 && common.Data.Count != 0)
common.Data.Clear();
}
}
}
比原版慢一点。如果您的属性不是ViewCommonItemVM,请更改代码以检查item.GetValue(this)是否产生正确的类型。