从对象列表中删除一列
本文关键字:一列 删除 对象 列表 | 更新日期: 2023-09-27 18:14:03
我有一个类如下:
public class Entity
{
public string Name {get;set;}
public int ID {get;set;}
public string Desc {get;set;}
}
我有Entity
的List
:
List<Entity> ent = new List<Entity>()
{
new Entity {Name ="A", ID =1},
new Entity {Name ="B", ID = 2}
};
在列表中,我们可以观察到"Desc"的值对于每个对象都是空的。有没有办法找出属性Name,它的值对于List中的所有对象都是空的?
在这个例子中,输出是"Desc",没有使用for循环,循环对象并保持标志?
使用LINQ:
var Properties = typeof(Entity).GetProperties()
.Where(propertyInfo => ent.All(entity => propertyInfo.GetValue(entity, null) == null))
.Select(c=>c.Name);
Properties
是String
的IEnumerable
,是Properties
的Name
的IEnumerable
,它们的值对每个对象都是空的。
可以使用type遍历该类型的属性。GetProperties方法,然后使用LINQ all方法和PropertyInfo检查列表中所有项的属性值是否为空。GetValue方法:
list<Entity> entities = ...;
foreach(PropertyInfo propertyInfo in typeof(Entity).GetProperties())
{
if(entities.All(entity => propertyInfo.GetValue(entity) == null))
{
Console.WriteLine("{0} property is null in all of the items in the list", propertyInfo.Name);
}
}