gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:18:00 25 4
gpt4 key购买 nike

我得到了一个特定对象的数组。让我们说对象汽车。在我的代码中的某个时刻,我需要从此数组中删除所有不满足我所述要求的汽车对象。这会在数组中留下空值。

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

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

我找到了无数关于字符串数组的解决方案,但没有找到一个对象数组。

最佳答案

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

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

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

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

关于C# 从对象数组中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28193564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com