[SOLVED] Get items from List A where Id is common in both List A and List B and counter of that Id is more than 1 in List A or List B

Issue

I was looking to get items from ListA, where the value of Id is same in both of the lists, and the count of Id must be more than 1 in list A or list B

var items = itemsA.Where(x => itemsB.Select(y => y.Id == x.Id).Count() > 1);

This gives me the result where same Ids in itemsB is more then 1, I want to use a or condition to check for the same counter in itemsA

Eg 1:
ListA=[{"id"=1,"name="abc"},{"id=1, "name"="def"}]
ListB=[{"id=2","name="xyz"}, {"id=1, "name"="mno"}]
Should return [{"id"=1,"name="abc"},{"id=1, "name"="def"}] because id =1 exists in listB and the count of id with value 1 in listA is more then 1.
Eg 2:
ListA=[{"id"=2,"name="abc"},{"id=1, "name"="def"}]
ListB=[{"id=1","name="xyz"}, {"id=1, "name"="mno"}]


should return {"id=1, "name"="def"} because common id in both list is 1 and the count of id with value 1 in ListB is more then 1.

Solution

I am not certain this is the best solution, but as far as I’ve understood the question, it should be a solution.

Assuming you have an Item class as follows:

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and define itemsA and itemsB as List<Item>s, you can first find all Ids that are present in both lists, then select the applicable items from itemsA based on occurrence of each Id in either list:

IEnumerable<int> idsInBothItemLists = itemsA
    .Select(a => a.Id)
    .Intersect(itemsB.Select(b => b.Id))
    .Distinct();

List<Item> items = itemsA
    .Where(a => idsInBothItemLists.Contains(a.Id))
    .GroupBy(a => a.Id)
    .Where(gr => 
        gr.Skip(1).Any() ||
        itemsB.Where(b => b.Id == gr.Key).Skip(1).Any())
    .SelectMany(gr => gr.Select(item => item))
    .ToList();

(.Skip(1).Any() serves the same purpose as .Count() > 1 in your original code; it simply checks whether there are any items left after skipping the first item.)


Printing the output from the suggested population of itemsA and itemsB

foreach (var entry in items)
{
    Console.WriteLine(entry.Id + " " + entry.Name);
}

e.g. for input

var itemsA = new List<Item>
{
    new Item { Id = 1, Name = "abc" },
    new Item { Id = 3, Name = "def" },
    new Item { Id = 1, Name = "ghi" },
    new Item { Id = 2, Name = "jkl" }
};

var itemsB = new List<Item>
{
    new Item { Id = 2, Name = "xyz" },
    new Item { Id = 2, Name = "jkl" },
    new Item { Id = 1, Name = "mno" },
    new Item { Id = 3, Name = "pqr" }
};

gives

1 abc
1 ghi
2 jkl

Answered By – Astrid E.

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *