Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LINQ to get items in one List<>, that are in another List<>

Tags:

c#

linq

I would assume there's a simple LINQ query to do this, I'm just not exactly sure how. Please see code snippet below, the comment explains what I'd like to do:

class Program
{
  static void Main(string[] args)
  {
    List<Person> peopleList1 = new List<Person>();
    peopleList1.Add(new Person() { ID = 1 });
    peopleList1.Add(new Person() { ID = 2 });
    peopleList1.Add(new Person() { ID = 3 });
    peopleList1.Add(new Person() { ID = 4});
    peopleList1.Add(new Person() { ID = 5});

    List<Person> peopleList2 = new List<Person>();
    peopleList2.Add(new Person() { ID = 1 });
    peopleList2.Add(new Person() { ID = 4});


    //I would like to perform a LINQ query to give me only
    //those people in 'peopleList1' that are in 'peopleList2'
    //this example should give me two people (ID = 1& ID = 4)
  }
}


  class Person
  {
     public int ID { get; set; }
  }
like image 200
ksg Avatar asked Nov 29 '22 23:11

ksg


1 Answers

var result = peopleList2.Where(p => peopleList1.Any(p2 => p2.ID == p.ID));

like image 194
Claudius Avatar answered Dec 10 '22 06:12

Claudius