Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.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#Linq返回数组中null/empty匹配项的第一个索引_C#_Linq - Fatal编程技术网

使用C#Linq返回数组中null/empty匹配项的第一个索引

使用C#Linq返回数组中null/empty匹配项的第一个索引,c#,linq,C#,Linq,我有一组字符串,叫做“Cars” 我想得到数组的第一个索引为null,或者存储的值为空。到目前为止,我得到的是: private static string[] Cars; Cars = new string[10]; var result = Cars.Where(i => i==null || i.Length == 0).First(); 但是,我如何获得此类事件的第一个索引 例如: Cars[0] = "Acura"; 然后索引应该返回1作为数组中的下一个可用点。您可以使用

我有一组字符串,叫做“Cars”

我想得到数组的第一个索引为null,或者存储的值为空。到目前为止,我得到的是:

private static string[] Cars;
Cars = new string[10];
var result = Cars.Where(i => i==null || i.Length == 0).First(); 
但是,我如何获得此类事件的第一个索引

例如:

Cars[0] = "Acura"; 
然后索引应该返回1作为数组中的下一个可用点。

您可以使用此方法

搜索匹配的元素 定义的条件 指定的谓词,并返回 从零开始的第一个索引 发生在整个数组中

例如:

int index = Array.FindIndex(Cars, i => i == null || i.Length == 0);

要了解适用于任何
IEnumerable
的更通用的方法,请查看:。

如果您希望使用LINQ方法,请参阅:

var nullOrEmptyIndices =
    Cars
        .Select((car, index) => new { car, index })
        .Where(x => String.IsNullOrEmpty(x.car))
        .Select(x => x.index);

var result = nullOrEmptyIndices.First();

可能不如
Array.FindIndex
简洁,但它可以用于任何
IEnumerable
而不仅仅是数组。它也是可组合的。

如果这些是字符串,为什么不使用
!string.IsNullOrEmpty(i)