I've been looking at this thread as a way to create a "smart" method for concatenating strings. I have a set of properties where some of them might be null, in which case, I'd like to remove them from the filtered list before using the String.Join method. So, I have something like this:
Dim filteredList = (New List(Of String) From {
a.ToString(),
b.ToString(),
c.ToString()
}).Where(Function(x) Not String.IsNullOrWhiteSpace(x))
Dim result As String = String.Join(" | ", filteredList)
There are instances where a, b, and/or c could be null. When I run this code, I get a null reference exception saying one of the properties .get returned nothing and the code bails. Is there a way to fix this?
Edit
I guess I could fix this by checking if a, b, or c were null before adding them to the list like this:
Dim fullList = New List(Of String)
If a IsNot Nothing Then fullList.Add(a.ToString())
If b IsNot Nothing Then fullList.Add(b.ToString())
If c IsNot Nothing Then fullList.Add(c.ToString())
Dim filteredList = fullList.Where(Function(x) Not String.IsNullOrWhiteSpace(x))
Dim result As String = String.Join(" | ", filteredList)
Is this the best way to handle this situation? Or is there a more elegant way?
a?.ToString()instead ofa.ToString()so that you get a null written into the list instead of a NullReferenceException.