Remove all NULL elements inside Generic List using C# and VB.Net

Last Reply 6 months ago By pandeyism

Posted 6 months ago

How to remove Null values form list?

here is my list

List<SamplingCS> returnlis = new List<SamplingCS>();   
returnlis.Add(new SamplingCS
             {
                 Sample_Size = SSample_Size,
                 Sample_Code = SSample_Code,
                 R_0_01 = SR_0_01,
                 R_0_015 = SR_0_015,
                 R_0_025 = SR_0_025,
                 R_0_04 = SR_0_04,
                 R_0_065 = SR_0_065,
                 R_0_1 = SR_0_1,
                 R_0_15 = SR_0_15,
                 R_0_25 = SR_0_25,
                 R_0_4 = SR_0_4,
                 R_0_65 = SR_0_65,
                 R_1 = SR_1
             });

 

Posted 6 months ago

Hi Sarasalvi,

Refer below sample.

Code

C#

protected void Remove(object sender, EventArgs e)
{
    List<SamplingCS> returnlis = new List<SamplingCS>();
    returnlis.Add(new SamplingCS { customerid = null, Name = null, Country = null });
    returnlis.Add(new SamplingCS { customerid = null, Name = "Test", Country = "India" });
    // Check if all property in SamplingCS is null then remove.
    returnlis.RemoveAll(x => x.GetType()
                            .GetProperties()
                            .Select(p => p.GetValue(x, null))
                            .All(p => p == null));
}

public class SamplingCS
{
    public string customerid { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

VB.Net

Protected Sub Remove(ByVal sender As Object, ByVal e As EventArgs)
    Dim returnlis As List(Of SamplingCS) = New List(Of SamplingCS)()
    returnlis.Add(New SamplingCS With {
        .customerid = Nothing,
        .Name = Nothing,
        .Country = Nothing
    })
    returnlis.Add(New SamplingCS With {
        .customerid = Nothing,
        .Name = "Test",
        .Country = "India"
    })
    returnlis.RemoveAll(Function(x) x.GetType().GetProperties().Select(Function(p) p.GetValue(x, Nothing)).All(Function(p) p Is Nothing))
End Sub

Public Class SamplingCS
    Public Property customerid As String
    Public Property Name As String
    Public Property Country As String
End Class