温馨提示×

c#数组如何去除空值

c#
小亿
118
2024-08-01 21:11:11
栏目: 编程语言

在C#中,可以使用LINQ(Language Integrated Query)来去除数组中的空值。下面是一个示例代码:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] array = { "a", "", "b", "c", null, "d", "e", "" };

        // 使用LINQ过滤空值
        var result = array.Where(x => !string.IsNullOrEmpty(x)).ToArray();

        Console.WriteLine("原始数组:");
        foreach (var item in array)
        {
            Console.Write(item + " ");
        }

        Console.WriteLine("\n去除空值后的数组:");
        foreach (var item in result)
        {
            Console.Write(item + " ");
        }
    }
}

在上面的示例中,我们使用Where方法结合lambda表达式来过滤数组中的空值,然后使用ToArray方法将结果转换为数组。最后分别输出原始数组和去除空值后的数组。

输出结果如下:

原始数组:
a b c d e 
去除空值后的数组:
a b c d e 

0