JerryKur
JerryKur

Reputation: 7519

linq to object using a list of tuples

I need to query a object collection in Entity framework and find the objects that meet a list of parameters. For example and object could contain fields (p1, p2, p3, p4, .. pn). I want to find the 3 objects for which the following are true (p1 = 3, p2 = 7, P3 =23), (p1 = 3, p2 = 43, p3 = 45), (p1 = 1, p2 =232, p3 = 321).

Since the collection could contain many elements and I could be looking for many (ex. 80) such tuples I do not want to do this in a loop since that would require a lot of round trips. I would prefer to do this is a single LINQ statement. Is this possible?

Thanks,

Jerry

Upvotes: 2

Views: 1889

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564403

Yes, you could do this. Just do:

var matches = entities.Where(e => 
       (e.p1 == 3 && e.p2 == 7 && e.p3 == 23)
    || (e.p1 == 3 && e.p2 == 43 && e.p3 == 45)
    || (e.p1 == 1 && e.p2 == 232 && e.p3 == 321));

Upvotes: 0

Snowbear
Snowbear

Reputation: 17274

You can try following approach, though I'm not sure that it will work with Linq-to-entity.

IEnumerable<Tuple<int, int, int>> criterias = ...;

var filteredObjects = DataContext.YourObjects
                .Join(criterias, 
                      o => new {o.P1, o.P2, o.P3}, // your objects key
                      c => new {o.P1, o.P2, o.P3}, // criteria key
                      (o, c) => o);

Upvotes: 1

Related Questions