开发者

What would this look like in Linq?

开发者 https://www.devze.com 2023-02-25 21:33 出处:网络
Hey everyone I\'m trying to get a clearer understanding of LINQ.I have a set of foreach loo开发者_StackOverflow社区ps that I use to loop through a list of IDs that I then compare to a list of object I

Hey everyone I'm trying to get a clearer understanding of LINQ. I have a set of foreach loo开发者_StackOverflow社区ps 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;
      }
   }
}


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);


It would look something like this:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消