-1

I have the following lists

var list1 = new List<Items>()
{
    new Items { Id = 1, Name = "PC" },
    new Items { Id = 2, Name = "Mug" },
    new Items { Id = 3, Name = "Table" },
    new Items { Id = 4, Name = "Table" }
};

var list2 = new List<string> { "Mug", "Table", "Buld" };

I am trying to get a list where list1 contains list2 without duplication

var list1 = new List<Items>()
{
    new Items { Id = 1, Name = "PC" },
    new Items { Id = 2, Name = "Mug" },
    new Items { Id = 3, Name = "Table" }
};

This is what I tried but does not work

var result = list1.Where(t1 => list2.Any(x => x == t1.Name)).ToList();
Bug
  • 832
  • 2
  • 9
  • 37
  • GroupBy + First, or Distinct with a comparer on Name. More linQ distinct By – Self Apr 15 '21 at 13:50
  • 1
    Does this answer your question? [How to get a distinct list from a List of objects?](https://stackoverflow.com/questions/4991728/how-to-get-a-distinct-list-from-a-list-of-objects) – Self Apr 15 '21 at 13:50
  • And [LINQ's Distinct() on a particular property](https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property) – Self Apr 15 '21 at 13:51
  • 1
    Why is `{ Id = 1, Name = "PC" }` included in the output, when "PC" isn't in `list2`? – Johnathan Barclay Apr 15 '21 at 13:52
  • @Self I still need to compare the two lists – Bug Apr 15 '21 at 13:53
  • So I should remove first the duplication and then compare both lists? – Bug Apr 15 '21 at 13:55
  • Filter then remove duplicate look the less taxing as you don't have to clear dupe that don't match. – Self Apr 15 '21 at 13:57
  • Your `list1.Where(t1 => list2.Any(x => x == t1.Name))` is equivalent to the proposed `list1.Where(item => list2.Contains(item.Name))`. The only missing part is the `.GroupBy(x => x.Property).Select(group => group.First())`. From the dupe target. – Self Apr 15 '21 at 14:04

1 Answers1

0

Something like this:

   var result = list1
     .Where(item => list2.Contains(item.Name)) // Name must be in list2
     .GroupBy(item => item.Name)
     .Select(group => group.First())  // no duplicates: 1st item from each group
     .ToList();

There's a question: when having duplicates which item should be taken. In the code above I take the item which appears first in the list1. If you want to take, say, the item with the smallest Id you should modify the Select:

      ...
      .Select(group => group.OrderBy(item => item.Id).First())
      ... 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215