开发者

Is there a concise way to determine if any object in a list is true?

开发者 https://www.devze.com 2023-04-01 03:24 出处:网络
I would like to create a test such that if a certain property is true for any Object in a list, the result would be true.

I would like to create a test such that if a certain property is true for any Object in a list, the result would be true.

Normally the way I would do it is:

foreach (Object o in List)
{
    if (o.property)
    {
        myBool = true;
        break;
    }
    myBool = false;
}

So my q开发者_如何转开发uestion is: Is there a more concise way of doing the same task? Maybe something similar to the following:

if (property of any obj in List)
    myBool = true;
else
    myBool = false;


Use LINQ and a Lambda Expression.

myBool = List.Any(r => r.property)


The answer here is the Linq Any method...

// Returns true if any of the items in the collection have a 'property' which is true...
myBool = myList.Any(o => o.property);

The parameter passed to the Any method is a predicate. Linq will run that predicate against every item in the collection and return true if any of them passed.

Note that in this particular example the predicate only works because "property" is assumed to be a boolean (this was implied in your question). Was "property" of another type the predicate would have to be more explicit in testing it.

// Returns true if any of the items in the collection have "anotherProperty" which isn't null...
myList.Any(o => o.anotherProperty != null);

You don't necessarily have to use lambda expressions to write the predicate, you could encapsulate the test in a method...

// 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);

You can also re-use that predicate in other Linq methods...

// Loop over only the objects in the list where the predicate passed...
foreach (Foo o in myList.Where(ObjectIsValid))
{
    // do something with o...
}


Yes, use LINQ

http://msdn.microsoft.com/en-us/vcsharp/aa336747

return list.Any(m => m.ID == 12);

Edit: changed code to use Any and shortened code


myBool = List.FirstOrDefault(o => o.property) != null;

I tried to use the same variables you did.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号