Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 539
hsop Avatar asked Jan 25 '16 11:01

hsop


2 Answers

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>();
}
like image 93
Steve Avatar answered Sep 17 '22 11:09

Steve


It's more clear:

casedata.Cases = casedata.Cases ?? new List<Case>();
casedata.Cases.AddRange(cases);

casedata.Documents = casedata.Documents ?? new List<Document>();
casedata.Documents.AddRange(documents);
like image 41
Andrey Burykin Avatar answered Sep 17 '22 11:09

Andrey Burykin