You can use the method Except
(System.Linq
) to solve the problem:
private IEnumerable<Carros> GetCarros(long userId, List<Carros> list)
{
var retornaCarros = _CarrosRepository.GetCarrosType(CarrosType.ROSA.Value, userId);
return list.Except(retornaCarros);
}
The method Except
returns a list of the elements from the first list (in your case, list
) which do not appear on the second list (retornaCarros
).
(If you want to return one List<Carros>
instead of IEnumerable<Carros>
call the method .ToList()
(Return list.Except(retornaCarros).ToList()
) and change the method signature.
(See an example in Dotnetfiddle.)
EDIT (Regarding the dcastro comment):
Indeed in the case of your class Carros
it is necessary that this knife override of the methods .GetHashCode()
and .Equals(object obj)
so that the .Except()
is successfully carried out.
However, it is not always possible to do these overrides. Thus, one way to solve the problem is to create a class that implements IEqualityComparer<Carros>
. An instance of this class can be passed to the .Except()
, which in turn will use it for comparison (rather than using the base class methods object
).
A possible implementation (assuming there is a property UniqueId
in class Carros
):
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 on how the IEqualityComparer
is used:
The method .Equals()
is invoked only if the hash codes both instances are equal. You can check this situation by changing .GetHashCode()
in the fiddle above.
A note, check if the result has elements and redundant in this case since iteration does not happen if there are no elements (and this forces the collection to be evaluated twice).
– Omni
@Omni Well observed.
– ramaral