1
public class Car
{
    private string _manufacturer = string.empty;        
    private string _color = string.empty;
    private string _modelLine= string.empty;

    public string Manufacturer
    {
        get { return _manufacturer; }
        set { _manufacturer= value; }
    }
    public string Color
    {
        get { return _color; }
        set { _color= value; }
    }
    public string ModelLine
    {
        get { return _modelLine; }
        set { _modelLine= value; }
    }
}

I have a List allCars, and I want to remove from the list all items that are in a second list List selectedCars. How can I accomplish this with LINQ?

I tried something similiar to:

List<Car> listResults = allCars.Except(selectedCars).ToList();

However it is not removing any items from the allCars list.

1
  • You can use ExceptBy in this question Commented Oct 1, 2013 at 19:40

2 Answers 2

7

LINQ stands for Language INtegrated Query. It is for querying. Removing items from a list isn't querying. Getting all of the items that you want to remove is a query, or getting all of the items that shouldn't be removed is another query (that's the one that you have).

To remove items from the list you shouldn't use LINQ, you should use the appropriate List tools that it provides for mutating itself, such as RemoveAll:

var itemsToRemove = new HashSet<Car>(selectedCars); //use a set that can be efficiently searched
allCars.RemoveAll(car => itemsToRemove.Contains(car));
Sign up to request clarification or add additional context in comments.

Comments

1

Sample Solution Code

    var item = new Car { Color = "red", Manufacturer = "bmw", ModelLine = "3" };
    var car = new Car { Color = "red", Manufacturer = "toyo", ModelLine = "2" };
    var item1 = new Car { Color = "red", Manufacturer = "marc", ModelLine = "23" };

    var carsa = new List<Car>
        {
            item1,
            item,
            car
        };
    var carsb = new List<Car>
        {
            item,
            car
        };

    carsa.RemoveAll(carsb.Contains);

2 Comments

Is this complete? Contains is a function.
RemoveAll takes a Predicate<T> as an argument, Contains is one of those too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.