-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();
8
  • GroupBy + First, or Distinct with a comparer on Name. More linQ distinct By Commented Apr 15, 2021 at 13:50
  • 1
    Does this answer your question? How to get a distinct list from a List of objects? Commented Apr 15, 2021 at 13:50
  • And LINQ's Distinct() on a particular property Commented Apr 15, 2021 at 13:51
  • 1
    Why is { Id = 1, Name = "PC" } included in the output, when "PC" isn't in list2? Commented Apr 15, 2021 at 13:52
  • @Self I still need to compare the two lists Commented Apr 15, 2021 at 13:53

1 Answer 1

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())
      ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.