Ivan_nn2
Ivan_nn2

Reputation: 469

Custom Func<> delegate inside Linq where clause

I should customize a Func expression so that I should make a check of an array of bytes inside of it a return true if are this array is equal to a field in a POCO..

So I don't know how to define it...

public Patient GetPatientByIdentificationCode(byte[] bytes)
    {
        return DbSet.Where(Func<>).FirstOrDefault();
    }

the Patient has an IdentificationCode that is an arrya of bytes...

thanks

Upvotes: 0

Views: 814

Answers (2)

D Stanley
D Stanley

Reputation: 152566

if the order of the bytes is part of the equality then you can use SequenceEqual:

return DbSet.Where(p => p.IdentificationCode.SequenceEqual(bytes)).FirstOrDefault();

If order doesn't matter then you can check that the elements are the same and the lengths are the same:

return DbSet.Where(p => 
                 p.IdentificationCode.Length == bytes.Length && 
                 p.IdentificationCode.Intersect(bytes).Count() == p.IdentificationCode.Length)
            .FirstOrDefault();

It will likely be slower than SequenceEqual so only use it if the order of the bytes isn't important.

As a side note I would STRONGLY suggest making this either a real method or extension method on Patient as I suspect you'll be using it A LOT.

Either that, or change to a more easily comparable (and displayable) type than an array of bytes.

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45083

In principle something like this should work:

return DbSet
  .Where(i => i.IdentificationCode.Length == bytes.Length)
  .FirstOrDefault();

If you could be more clear then we could maybe be more helpful. Specifically you could tell use if DbSet is a collection of Patient or not.

Upvotes: 1

Related Questions