Sadiq
Sadiq

Reputation: 2289

Is there a concise way to determine if any object in a list is 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 question 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;

Upvotes: 3

Views: 2730

Answers (4)

Rumplin
Rumplin

Reputation: 2768

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

Upvotes: 1

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

Use LINQ and a Lambda Expression.

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

Upvotes: 11

MattDavey
MattDavey

Reputation: 9027

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...
}

Upvotes: 3

Erik Philips
Erik Philips

Reputation: 54636

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

I tried to use the same variables you did.

Upvotes: 0

Related Questions