C#从对象数组中删除空值

kpp*_*kpp 15 c# arrays

我得到了一个特定对象的数组.让我们说对象车.在我的代码中的某些时候,我需要从这个数组中删除所有不符合我所述要求的Car-object.这会在数组中保留空值.

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
Run Code Online (Sandbox Code Playgroud)

当然,我的真实代码远比这复杂,但基本思想是一样的.我的问题是:如何从这个数组中删除空值?

我找到了无数的字符串数组解决方案,但没有找到对象数组.

JLR*_*she 30

以下将创建一个新数组,其中排除了所有空值(这似乎是你真正想要的?):

Cars = Cars.Where(c => c != null).ToArray();
Run Code Online (Sandbox Code Playgroud)

更好的是,定义你的 RemoveAllBMWs方法,首先省略BMW,而不是将它们设置为null:

internal static Car[] RemoveAllBMWs(IEnumerable<Car> cars)
{
    return cars.Where(c => c != null && c.Type != "BMW").ToArray();
}
Run Code Online (Sandbox Code Playgroud)