2016-10-20 4 views
1

私はクラスを持っている:オブジェクトのリストから列を排除

public class Entity 
{ 
    public string Name {get;set;} 
    public int ID {get;set;} 
    public string Desc {get;set;} 
} 

私が持っているListEntityの:リストで

List<Entity> ent = new List<Entity>() 
{ 
    new Entity {Name ="A", ID =1}, 
    new Entity {Name ="B", ID = 2} 
}; 

、私たちは "を観察することができてDesc "の値は、オブジェクトごとに空白です。 List内のすべてのオブジェクトで値が空のプロパティNameを見つける方法はありますか。

この例では、forループを使用せずにオブジェクトをループしてフラグを保持しないで、出力は "Desc"です。

答えて

2

は、LINQを使用します。

var Properties = typeof(Entity).GetProperties() 
       .Where(propertyInfo => ent.All(entity => propertyInfo.GetValue(entity, null) == null)) 
       .Select(c=>c.Name); 

PropertiesそのPropertiesNameIEnumerableあるStringIEnumerableありますir値はオブジェクトごとにnullです。

2

あなたは、リスト内のすべてのアイテムでプロパティ値がLINQ All方法とPropertyInfo.GetValue方法を使用してnullであることを確認した後、Type.GetProperties方法を使用したタイプのプロパティを反復処理することができます。

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); 
    } 
} 
関連する問題