TransWikia.com

How to concatenate 3 lists even if there are a list null?

Stack Overflow Asked by AlexZ on December 5, 2020

I have a problem when concatenating 3 lists, the problem is that it comes from a multi-select combo so I tried to concatenate the three lists even if they came empty but the "concatenate" instruction does not work with empty lists, someone could guide me.

if (model.Estatus.Count() < 3)
{
    if (model.Estatus.Contains(2))
    {
        var aut = listaCompleta.Where(x => x.Autorizada == true).ToList();
        listaAutorizada.Concat(listaCompleta.Where(x => x.Autorizada == true).ToList());
    }
    if (model.Estatus.Contains(3))
    {
        listaRechazada.Concat(listaCompleta.Where(x => x.Autorizada == false).ToList());
    }
    if (model.Estatus.Contains(4))
    {
        listaPendientes.Concat(listaCompleta.Where(x => x.Autorizada == null).ToList());
    }
    listaEstatus.Concat(listaAutorizada).Concat(listaRechazada).Concat(listaPendientes);
}

When a list is empty it turns the result list into null as well. What other alternative could you use to make the union of these lists?

2 Answers

This method can be used in many scenarios:

class Program
{
    static void Main()
    {
        var list1 = new List<string> { "bella", "ci" };
        var list2 = new List<string> { "bella", "ci" };
        List<string> list3 = null;

        var result = ConcatLists(list1, list2, list3);
    }

    public static List<T> ConcatLists<T>(params List<T>[] lists)
    {
        var outputList = new List<T>();

        foreach(var list in lists)
        {
            if (list != null)
                outputList.AddRange(list);
        }

        return outputList;
    }
}

Answered by Marco Salerno on December 5, 2020

You need to check for null with this code:

?? Enumerable.Empty<theListType>()

So your code should looks like this:

var result = (list1 ?? Enumerable.Empty<ListType>()).Concat(list2 ?? 
           Enumerable.Empty<ListType>()).Concat(list3 ?? Enumerable.Empty<ListType>());

Answered by Salah Akbari on December 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP