Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically use Concat to remove null lists

Tags:

json

c#

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.


1 Answers

You could use an extension method that handles the null value for a list. E.g.

    public static class EnumerableExtension
    {
        public static IEnumerable<TSource> ConcatOrDefault<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
        {
            if (second == null)
                return first;
            return first.Concat(second);
        }
    }

Then you can rewrite your statement to

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

Now values like _propertyList or _allSavings may be null. In this case just the unaltered sequence is returned.

like image 168
Ralf Bönning Avatar answered Mar 11 '26 14:03

Ralf Bönning