Add a List to another List that is either null or not null

hsop picture hsop · Jan 25, 2016 · Viewed 10.2k times · Source

Consider the the piece of code below. I need to call the method CreateOrAddToLists() in a loop. First time the method is called the two lists casedata.Cases and casedata.Documents will be null, hence I can populate by assigning cases to casedata.Cases like this:

casedata.Cases = cases;

At any subsequent call to CreateOrAddToLists() lists casedata.Cases and casedata.Documents will not be null and I can add new data to the lists using AddRange():

casedata.Cases.AddRange(cases);

var casedata = new CaseData(); //contains lists to get populated

private void CreateOrAddToLists()
{   
    var cases = new List<Case>(); //gets data with from database
    var documents = new List<Document>(); //gets data with from database

    if (casedata.Cases == null)
    {
        casedata.Cases = cases;
    }
    else
    {
        casedata.Cases.AddRange(cases);
    }
    if (casedata.Documents == null)
    {
        casedata.Documents = documents;
    }
    else
    {
        casedata.Documents.AddRange(documents);
    }
}

Is there a better or neater way to do a null-check before AddRange? Can I do it in on line of code?

Answer

Steve picture Steve · Jan 25, 2016

In the constructor for CaseData instantiate the two list objects, then you'll be assured they won't be null and you can just use AddRange.

public CaseData()
{
    Cases = new List<Case>();
    Documents = new List<Document>();
}