Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform Zip operation with null array

I'm experimenting with Zip operations in C#, like described here. Considering this code snippet:

int[] numbers = new[] { 1, 2, 3, 4 };
string[] words = new string[] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach (var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

What is a proper way to avoid System.ArgumentNullException in case one of the components are null?
For example, initializing words to null, like this

int[] numbers = new[] { 1, 2, 3, 4 };
string[] words = null;

// The next line won't work
var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });


Obs: I'm actually working with Directory.EnumerateDirectories and Directory.EnumerateFiles instead of int[] and string[].

like image 528
first timer Avatar asked Oct 23 '25 18:10

first timer


1 Answers

The following is kinda ugly, but you could use the null coalescing operator ?? like this:

var numbersAndWords = 
  (numbers ?? Enumerable.Empty<int>()).Zip(
        (words ?? Enumerable.Empty<string>()), 
        (n, w) => new { Number = n, Word = w });

Or create an extension method that does the same (you may want to come up with a better name than OrEmpty):

public static class MyEnumerableExtensions
{
    public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> self)
    {
        return self ?? Enumerable.Empty<T>();
    }
}

var numbersAndWords = numbers.OrEmpty()
    .Zip(words.OrEmpty(), (n, w) => new { Number = n, Word = w });
like image 65
Alex Avatar answered Oct 26 '25 07:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!