user793468
user793468

Reputation: 4966

string.join append character when null

I am using string.join to concatenate a string, I want to append ? whenever there is a NULL in the concatenated string.

Right now it shows up like this:

a,b,c,,e

I want to show like this:

a,b,c,?,e

linq:

    var listStr = (from c in cc.ccValues select c.ccValue).ToList();
    return string.Join(",", listStr);

Upvotes: 2

Views: 467

Answers (3)

dusky
dusky

Reputation: 1313

Just replace null with "?".

var strings = new List<string>{"a","b","c",null,"e"};
String.Join(",", strings.Select(s => s == null ? "?" : s));

Update

To get every string only once but replace every null string with "?" you can use LINQ's Distinct with an custom IEqualityComparer<T>.

var str = String.Join(",", strings.Distinct(new NullStringsAreDistinctComparer()).Select(s => s == null ? "?" : s));

The comparer could look like this:

class NullStringsAreDistinctComparer : IEqualityComparer<string> {

    public bool Equals(string x, string y) {
        return (x == null) ? y != null : x.Equals(y, StringComparison.InvariantCulture);
    }

    public int GetHashCode(string obj) {
        return (obj == null) ? 0 : obj.GetHashCode();
    }
}

Upvotes: 3

Khurram Ali
Khurram Ali

Reputation: 1679

string a ="a,b,c,,e,f,,h";
a.Replace(",,",",?,");

output : a,b,c,?,e,f,?,h

.NetFiddle

Upvotes: 0

Falanwe
Falanwe

Reputation: 4744

It's pretty easy, you just have to make a projection of your data beforehand.

Assuming you work with an IEnumerable<string> as data:

// replace null with "?"
var normalizedData = data.Select(s => s ?? "?");

return string.join(",", normalizedData);

Upvotes: 4

Related Questions