rogue39ni rogue39ni - 28 days ago 5
C# Question

How to dynamically use Concat to remove null lists

I am passing lists of the same type to a json file but as well all no if json finds a node it expects data in it I am having a problem where I am using the

concat
function but the lists will not always have assess in them so I need to no a way to be able to build the lists up dynamically.

List<Asset> AllAssets = allAssets.Concat(_vheiclesList)
.Concat(_propertyList)
.Concat(_securedLoansAssets)
.Concat(_allSavings)
.Concat(_allPensions)
.Concat(_allOtherAssets)
.ToList();


For example if there was no properties or savings then the list join would read like this.

List<Asset> AllAssets = allAssets.Concat(_vheiclesList)
.Concat(_securedLoansAssets)
.Concat(_allPensions)
.Concat(_allOtherAssets)
.ToList();


Each one of the lists is of type
asset
and then I also need to be able to tell the json to remove these so I need a way of adding each one via an if statement to check if
null
then don't concat it.

Answer

You can do this by constructing an array of arrays, then filtering out the null arrays(Where), then flattening the remaining arrays back into a single array (SelectMany).

List<Asset> AllAssets = new[]
    {
        allAssets,
        _vheiclesList,
        _propertyList,
        _securedLoanAssets,
        _allSavings,
        _allPensions,
        _allOtherAssets,
    }
    .Where(x => x != null)
    .SelectMany(x => x)
    .ToList();