Compare two lists of objects and pick up only the different [duplicate]

2

I'm having trouble comparing two lists of the same type List<Produto> in my product class I have the following structure.

public class Product
    {
        public int IdProduct { get; set; }
        public String Name { get; set; }

        public Supplier supplier { get; set; }

        public Product(){}
    }

And in my class of Supplier I have:

public class Supplier
{
    public int IdSupplier { get; set; }
    public string Main { get; set; }
    public string Name { get; set; }
}

And I make an initial list, and an ending list. The final contains more elements of products.

Test

List<Product> listaProdutosDiferentes = listaPrincipalProdutos.Union(listaFinalProdutos).ToList();

But this test just concatenated the two lists and did not pick up a list of different products from the other.

Issue

I have two lists, the first has some products that can be (id; name) 1, Motorola One Mobile; 2, Motorola G6 cell phone; 3, Motorola E5 mobile phone;

In my second list you will have the same list as the first one (not necessarily following a sequence).

5, Samsung Galaxy Phones; 1, Motorola One Mobile; 2, Motorola G6 cell phone; 3, Motorola E5 cell phone; 4, Iphone 6S phone;

My final list needs to be

1, Motorola One Mobile; 2, Motorola G6 cell phone; 3, Motorola E5 cell phone; 4, Iphone 6S Mobile Phone; 5, Samsung Galaxy Phones

Why do I do this? so that when a person searches through my system, the system will first present the search that the customer made, such as "Motorola phone", and then the other items that have a relationship, in this case other cell phones.

[Duplicate]

They marked as duplicate, but in the answer they left did not solve my problem I made the proposed codes, but all do not exclude the item that already has in the other list, I will show by the images:

Hereare4products.

Hereare9products

And on my list it should be the different list contains 9 products and not 5

    
asked by anonymous 30.10.2018 / 13:50

1 answer

3

You should use the Except() " of LINQ, which I use together lists without distinguishing what is already in the other.

var listaProdutosDiferentes = listaPrincipalProdutos.Except(listaFinalProdutos);

On the other hand you might want to do this (I can not say, the question is a bit ambiguous, see which produces the result you expect):

var listaProdutosDiferentes = listaPrincipalProdutos.Except(listaFinalProdutos).Concat(listaFinalProdutos.Except(listaPrincipalProdutos));

Or use Intersect() :

var listaProdutosDiferentes = listaPrincipalProdutos.Intersect(listaFinalProdutos);

Another point is that you should only use ToList() when you really need to make the list, it may even be your case, I can not dispute this, but I might not need it, so I preferred not to use it.

    
30.10.2018 / 14:18