mshwf
mshwf

Reputation: 7449

LINQ query checks if a set contain two records with specific values?

I'm looking for a query that returns true only if a set of data has at least one record with State == 0 AND another record with State > 0

I have this method:

  public bool HasHistory(Guid id)
        {
            return GetHistory(id).Any(x => x.State == 0); //&&x.State > 0 ?!
        }

I don't know how to accomplish this since most of the LINQ extention methods iterate over each element separately!

Upvotes: 2

Views: 122

Answers (4)

Aleks Andreev
Aleks Andreev

Reputation: 7054

You can use Aggregate method:

public bool HasHistory(Guid id)
{
    var result = GetHistory(id)
        .Aggregate(new { stateIsZero = true, stateIsPositive = true, hasItems = false },
        (a, x) => new
        {
            stateIsZero = a.stateIsZero && x.State == 0,
            stateIsPositive = a.stateIsPositive && x.State > 0,
            hasItems = true
        });
    return result.stateIsZero && result.stateIsPositive && result.hasItems;
}

But this approach will not work with IQueryable

Upvotes: 0

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

Simply use the &&- operator to combine the results of different queries:

public bool HasHistory(Guid id)
{
    var hist = GetHistory(id);
    return hist.Any(x => x.State == 0) && hist.Any(x => x.State > 0);
}

Upvotes: 2

Dmitry
Dmitry

Reputation: 518

    public bool HasHistory( Guid id )
    {
        var history = GetHistory( id );
        var check1 = false;
        var check2 = false;
        return history.Any( x =>
        {
            check1 = check1 || x.State == 0;
            check2 = check2 || x.State > 0;
            return check1 && check2;
        } );
    }

Upvotes: 3

Vladimir Arustamian
Vladimir Arustamian

Reputation: 842

What's wrong with this one?

  public bool HasHistory(Guid id)
  {
      var history = GetHistory(id);
      return history.Any(x => x.State == 0) && history.Any(x => x.State > 0);
  }

Actually, if you are working with big data, that's bad, because you are enumerating the collection 2 times instead of one. Otherwise, just use this solution.

Upvotes: 10

Related Questions