Remove null values from object array in C#
There are many ways to remove null objects from an Array in C#.1) Using Linq
2) Using Froeach
Remember to include all namespaces required by each example below.
Removing Null Objects using Linq
In below example we are going to use lambda expression supported by Linq usingWhere
syntax, and do a logical check on each element using IsNullOrEmpty()
Method.using System;
using System.Linq;
public class Car{
public string type { get; set; }
public Car(string ntype){
this.type = ntype;
}
}
public class Example
{
public static void Main()
{
string[] myColors = { "Red", "Blue", "", "Green", "", null, "pink" };
myColors = myColors.Where(color => !string.IsNullOrEmpty(color)).ToArray();
myColors.ToList().ForEach(i => Console.WriteLine(i.ToString()));
}
}
Output
Red
Blue
Green
pink
Blue
Green
pink
Removing Null Objects using Foreach
In below example we are going to use foreach to loop through all elements and check whether an element is null usingIsNullOrEmpty()
method.using System;
using System.Collections.Generic;
public class Car{
public string type { get; set; }
public Car(string ntype){
this.type = ntype;
}
}
public class Example
{
public static void Main()
{
string[] myColors = { "Red", "Blue", "", "Green", "", null, "pink" };
List<string> tempListColors = new List<string>();
foreach (string color in myColors)
{
if (!string.IsNullOrEmpty(color))
tempListColors.Add(color);
}
myColors = tempListColors.ToArray();
}
}