0

I need to compare two lists using two parameters of a class (same class) and add the difference to a third class. The Except() don't work for my situation.

I'm thinking of something like that, comparing XXX to YYY from another list:

var newList = List1.Select(x => x.XXX && x.YYY)
      .Except(List2.Select(x => x.XXX && x.YYY));

thanks!

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Guihenr1
  • 73
  • 8
  • 1
    Does this answer your question? [Linq Query To Combine 2 Lists](https://stackoverflow.com/questions/1930288/linq-query-to-combine-2-lists) – Mark Schultheiss Apr 30 '20 at 13:25
  • or maybe https://stackoverflow.com/q/23016768/125981 – Mark Schultheiss Apr 30 '20 at 13:27
  • or https://stackoverflow.com/q/720609/125981 - many answers like this to choose from – Mark Schultheiss Apr 30 '20 at 13:28
  • 1
    Care to elaborate why `Except` wont work but you then propose using `Except` on projections of the original lists as a viable option? You are aware you can pass in an `IEqualityComoparer` tailored to your specific needs when calling `Excecpt`, right? Maybe including a real example with similar data of your problem can help. – InBetween Apr 30 '20 at 13:40
  • Note this may also be that you need a not contains like this answer here https://stackoverflow.com/a/7348099/125981 – Mark Schultheiss Apr 30 '20 at 13:48

1 Answers1

2

Your current way can only get different data that exists in List1 but not in List2.

To get all their different data, you also need to reverse except and merge them by Union.

Here is my class Product:

public class Product
        {
            public int Id { get; set; }  
            public string Title { get; set; }
            public string Description { get; set; }
        }

Here is the code:

  List<Product> List1 = new List<Product>()
        {
            new Product(){   Id =1, Title="aaa", Description="cccccccc" },
             new Product(){  Id =2,Title="bbb", Description="cccccccc" },
              new Product(){  Id =3, Title="ccc", Description="cccccccc"  },
        };
        List<Product> List2 = new List<Product>()
        {
            new Product(){  Id =1, Title="aaa" , Description ="csdfsdf"},
             new Product(){  Id =4, Title="bbb" , Description ="cccccccccc"},
        };
        var newList= (List1.Select(x => new { x.Id, x.Title }).Except(List2.Select(x => new { x.Id, x.Title })).
            Union(List2.Select(x => new { x.Id, x.Title }).Except(List1.Select(x => new { x.Id, x.Title })))).ToList();

Here is the test process:

enter image description here

LouraQ
  • 6,443
  • 2
  • 6
  • 16