You can use the Except
method. ( System.Linq
) to resolve the problem:
private IEnumerable<Carros> GetCarros(long userId, List<Carros> list)
{
var retornaCarros = _CarrosRepository.GetCarrosType(CarrosType.ROSA.Value, userId);
return list.Except(retornaCarros);
}
The Except
method returns a list with elements of the first list (in this case, list
) that do not appear in the second list ( retornaCarros
).
(If you want to return List<Carros>
instead of IEnumerable<Carros>
call method .ToList()
(return list.Except(retornaCarros).ToList()
) and change the method signature.
(See an example in DotNetFiddle.)
EDIT (Relatively to Dcastro's comment):
In fact, in the case of its class Carros
it is necessary that this knife override methods .GetHashCode()
and .Equals(object obj)
so that .Except()
is successful.
However, it is not always possible to do these overrides . So, one way to solve the problem is to create a class that implements IEqualityComparer<Carros>
. An instance of this class can be passed to .Except()
, which in turn will use it to make the comparison (instead of using the methods of the base class object
).
A possible implementation (assuming there is a UniqueId
property in the Carros
class):
public class CarrosComparer: IEqualityComparer<Carros>
{
public int GetHashCode(Carros carro)
{
return carro.UniqueId;
}
public bool Equals(Carros carro1, Carros carro2)
{
return carro1.UniqueId == carro2.UniqueId;
}
}
Then you can do the following:
private IEnumerable<Carros> GetCarros(long userId, List<Carros> list)
{
var retornaCarros = _CarrosRepository.GetCarrosType(CarrosType.ROSA.Value, userId);
return list.Except(retornaCarros, new CarrosComparer());
}
(See an example in DotNetFiddle.)
An interesting note about how IEqualityComparer
is used:
The .Equals()
method is only invoked if the hash codes of both instances are equal. You can check this by changing .GetHashCode()
in fiddle above.