0

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?

1
  • Since your filter function can handle a null, you could add a?.ToString() instead of a.ToString() so that you get a null written into the list instead of a NullReferenceException. Commented Jul 11, 2022 at 14:02

1 Answer 1

2

Calling the ToString() method on a null object will result in a NullReferenceException.

Instead, you will need to:

  1. Filter to return just the values that are not null
  2. Select the value of ToString on the filtered set
  3. Then join

Also, there really is no need to convert the array to a List.

E.g.

Dim filteredList = { a, b,  c }
    .Where(Function(x) x IsNot Nothing)
    .Select(Function(x) x.ToString())

Dim result As String = String.Join(" | ", filteredList)

Example: https://dotnetfiddle.net/Epwk3Q

Sign up to request clarification or add additional context in comments.

1 Comment

@Craig - You're right. For some reason I didn't think that String.Join supported IEnumerable and erroneously believed that the conversion would be implicit. After consulting the documentation, it appears the IEnumerable overload has been supported since .NET framework 4.0 (and I doubt the OP is targeting anything less).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.