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

StackOverflow https://stackoverflow.com/questions/20354044

  •  25-08-2022
  •  | 
  •  

Question

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"

Was it helpful?

Solution

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

Try using Concat instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top