0

Hi I am new to List handling. Please help me how to remove the null elements from the List.

Let me explain my question with an example. The below are the two class which I have.

public class Student
{
    public int id{get;set;}
    public string Name{get;set;}
    public Book book{get;set;}
}

public class Book
{
    public String BookName{get;set;}
    public int BookId{get;set;}
}

The below data i am binding to Student class. Which in result we get the List.

{
Student: {"id":1,"Name":"John","book":{"BookName":"Math","BookId":1}},
Student: {"id":3,"Name":"John","book":{"BookName":"Math","BookId":2}},
Student: {"id":4,"Name":"John","book":null},
}

Here I want to remove the fields, if it contains null value and send these data in json format.

Ultimately the required format is as below.

{
Student: {"id":1,"Name":"John","book":{"BookName":"Math","BookId":1}},
Student: {"id":3,"Name":"John","book":{"BookName":"Math","BookId":2}},
Student: {"id":4,"Name":"John"},
}

Please note that there should not any fields with null value.

4
  • What have you tried? You need to loop through the list and remove elements if they are null. Commented Feb 14, 2018 at 11:02
  • 3
    The title is misleading, you want to avoid serializing a property that has a null value. Commented Feb 14, 2018 at 11:03
  • As @LasseVågsætherKarlsen mentioned, please see following link: stackoverflow.com/a/6507965/4222487 Commented Feb 14, 2018 at 11:08
  • 1
    @FaizanRabbani Question has already been duped to that question :) Commented Feb 14, 2018 at 11:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.