0
我有一个列表,其中TestClass是一个具有一些预定义属性的类。所以当我得到数据并绑定我的列表与数据时,我需要通过将它与列表进行比较来忽略TestClass的某些属性。我怎么能做到这一点?通过与c中的列表比较来忽略类的属性
下面是我的代码
public class TestClass
{
public int id{get;set;}
public string fname{get;set;}
public string lname{get;set;}
public string job {get;set;}
public string role{get;set;}
public string address{get;set;}
}
List<TestClass> ulist = null;
ulist = ToList<TestClass>(usersdataset.tables[0]); //fill my list with the data code is given below
所以获取数据到列表后,我需要通过与属性列表,它应该是,如果我的filteredlist应该只出示身份证returned.for例子比较删除某些属性,fname,角色然后我需要从我的ulist删除额外的属性。所以过滤器ulist应当只包含ID,FNAME和作用
ToList方法
public static List<T> ToList<T>(DataTable dataTable) where T : new()
{
var dataList = new List<T>();
//Define what attributes to be read from the class
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
//Read Attribute Names and Types
var objFieldNames = typeof(T).GetProperties(flags).Cast<PropertyInfo>().
Select(item => new
{
Name = item.Name,
Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
}).ToList();
//Read Datatable column names and types
var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
Select(item => new {
Name = item.ColumnName,
Type = item.DataType
}).ToList();
foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var classObj = new T();
foreach (var dtField in dtlFieldNames)
{
PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);
var field = objFieldNames.Find(x => x.Name == dtField.Name);
//var field = filteredColumns.Find(x => x.PropertyName == dtField.Name);
if (field != null)
{
if (dataRow[dtField.Name] != DBNull.Value)
propertyInfos.SetValue(classObj, dataRow[dtField.Name], null);
}
}
dataList.Add(classObj);
}
return dataList;
}
什么是你的代码有错?我可以看到它可以更简洁高效,但会导致错误?你到底在寻找什么帮助 – CharlesNRice
你可以传递一个'List'到'ToList',它包含你想忽略的属性名称列表?然后在你的循环foreach(dtlFieldNames.Where(f =>!ignoreList.Contains(f))中的var dtField)中,那么你将永远不会填充它们。否则,你将不得不再次使用反射来遍历每个项目在你的列表中,并且使用Reflection'GetProperties'再一次清空每个属性 –
pinkfloydx33
只需要注意:由于整个函数的“T”保持不变,因此不需要PropertyInfo propertyinfos = classObj ..在你的循环中,将它移动到顶端var props = typeof(T).GetProperties(flags).ToDictionary(x => x.Name)'',然后用'var propertyInfos = props [dtField.Name];'这样你就可以继续重复使用PropertyInfo对象,而不必一直用Reflection来查找它(尽管是不同的对象,PropertyInfo对象是相同的 - 因此第一个参数是SetValue )'在哪里指定要调用它的对象) – pinkfloydx33