Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# remove null values from object array

Tags:

arrays

c#

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.

like image 255
kpp Avatar asked Jan 28 '15 13:01

kpp


1 Answers

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();
}
like image 149
JLRishe Avatar answered Oct 31 '22 03:10

JLRishe