2016-09-22 51 views
-1

我想检查我的集合中的所有项目是否具有特定的属性值,假设我有一个名为IsFavourite的属性,我需要检查这个属性对于每个元素是否为true。我试过这个:如何检查集合中的所有项目是否具有特定的属性值?

var c = listView.Items.Cast<Event>().Where(x => x.MatchNation == nation 
     && x.MatchLeague == league && x.IsFavourite == true).Any(); 

但是这只会返回一个具有此属性的项目。

+2

将'Any()'改为'All()',你也不需要'== true',你可以简单地写'&& x.IsFavourite'。 –

+1

只需使用'All'而不是'Any'。 – Mormegil

回答

6

你必须使用All()

bool result = listView.Items.Cast<Event>() 
         .Where(x => x.MatchNation == nation && x.MatchLeague == league) 
         .All(x => x.IsFavourite); 
1

您需要使用All

var c = listView.Items.OfType<Event>().Where(x => x.MatchNation == nation 
     && x.MatchLeague == league).All(x => x.IsFavourite); 
2

您还可以使用Any(),但你检查是否有物品不IsFavourite(IsFavourite==false)。

var z = listView.Items.OfType<Event>().Where(x => x.MatchNation == nation 
      && x.MatchLeague == league).Any(x => x.IsFavourite==false); 
+0

但您必须更改变量名称,例如将'allAreFavourites'更改为'anyNonFavourite'。意思是不同的。 –