Reputation: 4966
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
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
Reputation: 1679
string a ="a,b,c,,e,f,,h";
a.Replace(",,",",?,");
output : a,b,c,?,e,f,?,h
Upvotes: 0
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