Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

How to determine if all objects inside List<T> has the same property value using Linq

I believe its not a hard one, but could not found anything.
I have a List of objects and i would like to write a query to determine if a specific property of all the objects has the value of 1 or not.
I would like to do that using LINQ \ Lambda.

    private bool IsTheSame(List<ContenderLeague> TryUpgradeConts)
    {
        bool IsTheSameValue = true;
        foreach (ContenderLeague c in TryUpgradeConts)
        {
            if (c.Contender.Factor != 1)
            {
                IsTheSameValue = false;
                break;
            }
        }
        return IsTheSameValue;
    }

Upvotes: 1

Views: 2711

Answers (3)

Igor
Igor

Reputation: 62213

using System.Linq; // at the top of your code file

Altered code

var allHaveContederFactorValueOne = TryUpgradeConts.All(i => i.Contender.Factor == 1);

Learn how to use lambdas expressions and the various built in functions in the framework like All, Any, Where, etc. They make coding much easier.

Upvotes: 8

ocuenca
ocuenca

Reputation: 39326

What you describe is using All extension method as you can see in the other answers:

return TryUpgradeConts.All(c=>c.Contender.Factor == 1);

But the real translation of your code is using Any:

return TryUpgradeConts.Any(c=>c.Contender.Factor != 1);

You are trying to find some element which doesn't meet the condition

Upvotes: 7

Shane Ray
Shane Ray

Reputation: 1459

Use the linq .All() method. Something like below should work.

private bool IsTheSame(List<ContenderLeague> TryUpgradeConts)
{
    return TryUpgradeConts.All(c => c.Contender.Factor == 1);
}

Upvotes: 2

Related Questions