Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Where clause with Contains where the list has complex object

Tags:

c#

linq

I've seen plenty of examples of LINQ with a contains on a simple list of objects:

var intList= new List<int>() { 1, 2, 3 };
var result = db.TableRecords.Where(c => intList.Contains(c.RecordId)).ToList();

What I'm trying to do seems slightly more complicated (I think). I have a line of code similar to this one gets me the list I need:

var xzList = db.Relations.Where(r => someOtherList.Contains(r.zId))
                         .Select(r => new { AId = r.xId, BId = r.zId })
                         .ToList();

And now I want to get the result similar to the previous example but the list now has an anonymous type in it with two ints. So how would I now get result where RecordId in TableRecords equals the AId in the anonymous type for each anonymous type in xzList?

like image 860
Sailing Judo Avatar asked Dec 27 '12 22:12

Sailing Judo


1 Answers

Sounds like you are unsure how to get the values out of your anonymous type. You can use GunnerL3510's solution to dump it to a list, or you should be able to inline it like this:

var result = 
    db.TableRecords
        .Where(c => xzList.Select(n => n.AId)
            .Contains(c.RecordId))
        .ToList();

Since you are naming the values in your anonymous type, you refer to them just like properties.

If you prefer to do a more structured approach, you can use this method.

like image 141
Jon Peterson Avatar answered Oct 12 '22 23:10

Jon Peterson