C# 是否有一种简洁的方法来确定列表中的任何对象是否为真?
我想创建一个测试,如果某个属性对于列表中的任何对象为true,那么结果将为true 通常我会这样做:C# 是否有一种简洁的方法来确定列表中的任何对象是否为真?,c#,linq,C#,Linq,我想创建一个测试,如果某个属性对于列表中的任何对象为true,那么结果将为true 通常我会这样做: foreach (Object o in List) { if (o.property) { myBool = true; break; } myBool = false; } 所以我的问题是:有没有更简洁的方法来完成同样的任务?可能与以下类似: if (property of any obj in List) myBoo
foreach (Object o in List)
{
if (o.property)
{
myBool = true;
break;
}
myBool = false;
}
所以我的问题是:有没有更简洁的方法来完成同样的任务?可能与以下类似:
if (property of any obj in List)
myBool = true;
else
myBool = false;
是的,使用LINQ
编辑:将代码更改为使用Any
和缩短的代码使用和a
myBool=List.Any(r=>r.property)
这里的答案是Linq Any方法
// Returns true if any of the items in the collection have a 'property' which is true...
myBool = myList.Any(o => o.property);
// Predicate which returns true if o.property is true AND o.anotherProperty is not null...
static bool ObjectIsValid(Foo o)
{
if (o.property)
{
return o.anotherProperty != null;
}
return false;
}
myBool = myList.Any(ObjectIsValid);
传递给Any方法的参数是谓词。Linq将对集合中的每个项运行该谓词,如果其中任何项被传递,则返回true
请注意,在这个特定示例中,谓词仅起作用,因为“property”被假定为布尔值(这在您的问题中暗示)。如果是另一种类型的“属性”,则谓词在测试时必须更显式
// Returns true if any of the items in the collection have "anotherProperty" which isn't null...
myList.Any(o => o.anotherProperty != null);
您不必使用lambda表达式来编写谓词,您可以将测试封装在一个方法中
// Returns true if any of the items in the collection have a 'property' which is true...
myBool = myList.Any(o => o.property);
// Predicate which returns true if o.property is true AND o.anotherProperty is not null...
static bool ObjectIsValid(Foo o)
{
if (o.property)
{
return o.anotherProperty != null;
}
return false;
}
myBool = myList.Any(ObjectIsValid);
您还可以在其他Linq方法中重用该谓词
// Loop over only the objects in the list where the predicate passed...
foreach (Foo o in myList.Where(ObjectIsValid))
{
// do something with o...
}
我尝试使用与您相同的变量。是的,请使用LINQ,但不要使用“Count()>0”,因为您需要处理整个列表以获得计数,然后进行计算。找到第一个匹配项后,使用“Any()”使评估短路。另外,不要执行“如果(条件)返回true”;否则返回false;',只需执行“返回条件;”