Skip to content
Advertisement

Return a list of elements that are NOT in two previous lists

I have 2 lists of IDs and I need to return a list with the products that aren’t in any of those lists:

 public IEnumerable<Produto> GetProdutosIdNotInFamily(Guid produtoId)
        {
            var produtosPai = GetListaPaisId(produtoId);

            var produtosFilho = GetListaFilhosId(produtoId);

            
            var prod = _dbContext.Produtos
                         .Where(u => !produtosPai.Any(p => p.ProdutoFilhoId == u.Id)
                               && !produtosFilho.Any(p => p.ProdutoFilhoId == u.Id));

            return prod;
        }

Advertisement

Answer

You can do this in two ways — One using Contains and other using Any like you provided in your snippet in the post.

Using Contains Method

If you want to use Contains() method, you may be pulling out all the product Ids into a collection and apply LINQ on top of it and get the list that is not part of both your reference lists. Sample code is as shown below

// This is the sample model I am dealing with
public class Dummy
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Assuming the below call returns list of 'Dummy' objects
var products = _dbContext.Produtos;

// list1 & list2 are populated in your case already through the method calls
var exclusionList1 = list1.Select(x => x.Id).ToList<int>();
var exclusionList2 = list2.Select(x => x.Id).ToList<int>();

var myList = products.Where(x => !exclusionList1.Contains(x.Id) && !exclusionList1.Contains(x.Id)).ToList();

Contains is an instance method and takes an object as a parameter and the time complexity depends on the collection you’re using this on.

Using Any

Just like Where, Any is an extension method. It takes a delegate as a parameter which gives you greater flexibility and control with respect to what you would want to do.

Applying Any to your scenario is as shown below:

var products = _dbContext.Produtos;

var exclusionList1 = GetListaPaisId(produtoId);
var exclusionList2 = GetListaFilhosId(produtoId);

var prod = _dbContext.Produtos.Where(x => !exclusionList1.Any(z => x.Id == z.Id) && 
!exclusionList2.Any(z => x.Id == z.Id)).ToList();

You can choose your approach based on the context under which you are performing this operation.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement