25

I got an array of a specific object. Lets say the object Car. At some point in my code I need to remove all Car-objects from this array that do not fulfill the requirements I stated. This leaves null values in the array.

public class Car{
    public string type { get; set; }

    public Car(string ntype){
        this.type = ntype;
    }
}

Car[] cars = new Car[]{ new Car("Mercedes"), new Car("BMW"), new Car("Opel");

//This should function remove all cars from the array where type is BMW.
cars = removeAllBMWs(cars);

//Now Cars has become this.
Cars[0] -> Car.type = Mercedes
Cars[1] -> null
Cars[2] -> Car.type = Opel

//I want it to become this.
Cars[0] -> Car.type = Mercedes
Cars[1] -> Car.type = Opel

Of course my real code is far more complex than this, but the base idea is the same. My question that I have is: How can I remove the empty values from this array?

I found countless solutions for a string array, but none for an object array.

8
  • 1
    "I found countless solutions for a string array, but none for an object array" - pretty sure they'll work for Car as well as they work for string... Commented Jan 28, 2015 at 13:34
  • they all use string.isemptyornull Commented Jan 28, 2015 at 13:34
  • 2
    So just replace that with == null. Commented Jan 28, 2015 at 13:35
  • 2
    Why not just use a list instead of an array? then you wont have any nulls Commented Jan 28, 2015 at 13:35
  • 1
    @kpp - You seem to have written the removeAllBMWs method yourself (or your team has) so I'd say just make that return a list since you are already modifying the array Commented Jan 28, 2015 at 13:41

1 Answer 1

51

The following will create a new array with all the null values excluded (which seems to be what you actually want?):

Cars = Cars.Where(c => c != null).ToArray();

Better yet, define your RemoveAllBMWs method to omit the BMWs in the first place instead of setting them to null:

internal static Car[] RemoveAllBMWs(IEnumerable<Car> cars)
{
    return cars.Where(c => c != null && c.Type != "BMW").ToArray();
}
Sign up to request clarification or add additional context in comments.

3 Comments

But the question is why he first uses a method removeAllBMWs which modifies the array in a way that it assigns null to every BMW. You could do both in one with cars.Where(c => c.type == "BMW").ToArray()
@TimSchmelter, this is a simplified version. I do not personally instantiate the array I receive it via a webservice from another application. Not all values in this array are useful though.
@TimSchmelter True, though I think you meant !=, not ==. I've added an addendum.

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.