Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Join dropping null values returning less items than number of Elements in the Array

Tags:

c#

Given this method, The resulting string created drops the consecutive null values. Is th ?? being used wrong below? It's behaving as if it is concatentating all consectively indexed null values before returning

 public static IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
        {
            FieldInfo[] fields = typeof(T).GetFields();
            PropertyInfo[] properties = typeof(T).GetProperties();
            yield return String.Join(separator, fields.Select(f => f.Name).Union(properties.Select(p => p.Name)).ToArray());
            foreach (var o in objectlist)
            {
                var pp = properties.Select(
                    p => (p.GetValue(o, null) ?? String.Empty));

                var val = string.Join(separator, fields.Select(f => (f.GetValue(o)).ToString() )
                    .Union(pp).ToArray());
                ;
                yield return val;
            }
        }

Here is my array

[0]"0001020003"
[1]"Bob Jones"
[2] NULL
[3] NULL
[4] "Longboat"

With that array the joined string created is...

"0001020003,Bob Jones,,Longboat"

like image 831
Doug Chamberlain Avatar asked Dec 02 '25 05:12

Doug Chamberlain


1 Answers

Enumerable.Union excludes duplicates, so you are only getting a single blank instance returned.

Try using Concat instead.

like image 143
samjudson Avatar answered Dec 03 '25 18:12

samjudson



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!