Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#从对象数组中删除空值_C#_Arrays - Fatal编程技术网

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

C#从对象数组中删除空值,c#,arrays,C#,Arrays,我得到了一个特定对象的数组。让我们说目标车。在我的代码中的某个时刻,我需要从这个数组中删除所有不满足我所述要求的Car对象。这会在数组中留下空值 public class Car{ public string type { get; set; } public Car(string ntype){ this.type = ntype; } } Car[] cars = new Car[]{ new Car("Mercedes"), new Car("B

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

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
当然,我真正的代码远比这复杂,但基本思想是一样的。我的问题是:如何从这个数组中删除空值


我为字符串数组找到了无数种解决方案,但对于对象数组却没有一种解决方案。

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

更好的方法是,首先定义
RemoveAllBMWs
方法以忽略bmw,而不是将其设置为null:

internal static Car[] RemoveAllBMWs(IEnumerable<Car> cars)
{
    return cars.Where(c => c != null && c.Type != "BMW").ToArray();
}
internal static Car[]拆卸所有BMW(IEnumerable cars)
{
返回车辆。其中(c=>c!=null和&c.Type!=“BMW”).ToArray();
}

“我发现了无数个字符串数组的解决方案,但没有一个用于对象数组”-非常确定它们适用于
Car
,也适用于
string
…它们都使用string.isemptyornull,所以只要用
==null
替换即可。为什么不直接使用
列表来代替数组呢?那你就没有了nulls@kpp-您似乎自己(或您的团队)编写了
removeAllBMWs
方法我想说的是,既然你已经在修改数组了,就让它返回一个列表吧。但问题是,为什么他首先使用一个方法
removeAllBMWs
,该方法修改数组的方式是将
null
分配给每个BMW。你可以在一辆
汽车上同时完成这两项工作。其中(c=>c.type==“BMW”).ToArray()
@TimSchmelter,这是一个简化版本。我个人不会实例化通过Web服务从另一个应用程序接收的阵列。不过,并不是这个数组中的所有值都有用。@TimSchmelter-True,不过我认为您的意思是
=,而不是
==
。我增加了一个附录。
internal static Car[] RemoveAllBMWs(IEnumerable<Car> cars)
{
    return cars.Where(c => c != null && c.Type != "BMW").ToArray();
}