Linq Compare two lists of different types

Asked

Viewed 3,602 times

4

I have two different lists A List<ProdutoTag> and B = List<Tag>:

public class ProdutoTag
{
    public Int64 ProdutoId { get; set; }
    public Int32 TagId { get; set; }
    public Double Peso { get; set; }
    public virtual Tag Tag { get; set; }
    public virtual Produto Produto { get; set; }
}

public class Tag
{
    public Int32 TagId { get; set; }
    public String Descricao { get; set; }

    public virtual ICollection<ProdutoTag> ProdutosTags { get; set; }
    public virtual ICollection<Resposta> Respostas { get; set; }        
}

I need to check that list A contains all the elements on list B (If List A contains other elements which List B does not possess, this is correct, but List A must have all elements of List B).

The way to compare the two lists is through Property A.

It would look something like (where x.Productostags is my A list):

// Busco na base de dados todos os produtos
var produtos = _context.Produtos.ToList();
// Agora preciso apenas dos produtos que contenham todas as tags selecionadas
var selecionados = produtos.Where(x => x.ProdutosTags.Contains(B));

How can I compare two lists of different types?

1 answer

8


Thus:

var aContemB = !b.Except(a.Select(p => p.Tag).ToList()).Any();

That is, it checks if any item of B is an exception to A, and checks whether the result has elements.

If there is an error, try to materialize the two lists before the comparison, ie:

var listaA = a.Select(p => p.Tag).ToList();
var listaB = b.ToList(); // Isto garante que todos os SQL foram executados antes da comparação.
var aContemB = !listaB.Except(listaA).Any();
  • Thanks for the help. I used var aContemB = !tags.Except(produtos.Select(p => p.ProdutosTags.Select(x => x.Tag)).ToList()); and I’m getting the error: Instance argument: cannot Convert from 'System.Collections.Generic.List<Domain.Entities.Tag>' to 'System.Linq.Parallelquery<System.Collections.Generic.Ienumerable<Domain.Entities.Tag>>' What I’m doing wrong?

  • I think you will have to run the commands separately. I will improve the example.

  • Thanks a lot for the help, but it hasn’t worked out yet. I have a list of products. Each product on this list has a list of Tags (Tagproduct). I only need to get products whose tags are the same as on my B list (where B lists tags)

  • This I think would already be another question, which goes beyond the scope of this question. I would like to open another question?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.