MrB
MrB

Reputation: 1594

What would this look like in Linq?

Hey everyone I'm trying to get a clearer understanding of LINQ. I have a set of foreach loops that I use to loop through a list of IDs that I then compare to a list of object IDs and then add them to a 3rd list that holds the result or the comparing. I was wondering what this bit of code would look like in LINQ list1 -> List of int Ids list2 -> List of Objects


foreach (var mId in list1)
{
   foreach (var m in list2)
   {
      if (m.Obj.Id== mId)
      {
        result.Add(m);
        break;
      }
   }
}

Upvotes: 0

Views: 108

Answers (3)

Iain Ward
Iain Ward

Reputation: 9936

It would look something like this:

var result = list2.Where(i => list1.Contains(i.Obj.Id));

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245429

Basically, that is the loop logic to perform a join. Using query syntax (which is more readable) you could do:

var result = from mId in list1
             join m in list2 on m.Obj.Id equals mId
             select m;

Or, if lambda's are your thing:

var result = list1.Join(list2, 
                        mId => mId, 
                        m => m.Obj.Id,
                        (mId, m) => m);

Upvotes: 8

Femaref
Femaref

Reputation: 61437

var query = list1.Join(list2, x => x, x => x.Obj.Id, (outer, inner) => inner);

Upvotes: 1

Related Questions