Home > Software design >  Get items with same values in properties in different list
Get items with same values in properties in different list

Time:11-25

I have two list of the same type of object (X)

X has this properties:

  • Id: int
  • Name: string
  • Month: string
  • ISSPA: string

I want to get the items which has the same value in the properties Month and ISSPA. For example:

List 1

Item 1 
{
   Id = 1, 
   Name = "John",
   Month = "October"
   ISSPA = "1234"
}

Item 2
{
   Id = 2, 
   Name = "Ryan",
   Month = "September"
   ISSPA = "1234"
}

List 2

Item 1 
{
   Id = 1, 
   Name = "Chris",
   Month = "September"
   ISSPA = "1234"
}

In this case I need to get Item 2 (List1) and Item 1 (List2). I tried a lot of things to get something decent but all failed.

CodePudding user response:

var result = list1
                .Concat(list2)
                .GroupBy(x => (x.Month, x.ISSPA))
                .Where(g => g.Count() > 1)
                .SelectMany(g => g);

CodePudding user response:

You can use LINQ to search for these items in your lists. For example:

var filteredList = yourList.Where(x => x.Month == "September" && x.ISSPA == "1234").ToList();

Simply do the same thing for your second list and combine both results into a new list.

  •  Tags:  
  • c#
  • Related