return results.Select(x => new {
VillageName = x.VillageName,
GroupID = x.GroupID,
GroupName = x.GroupName,
CenterID = x.CenterID,
CenterName = x.CenterName,
}).ToList<object>();
Asked
Active
Viewed 682 times
-1

David Pilkington
- 13,528
- 3
- 41
- 73

Prasad Mahanti
- 1
- 2
-
if CenterName and group name is null. Need to return an empty string In c# 6.0, x?.CenterName -> return null value – Prasad Mahanti Sep 10 '19 at 04:28
-
1I assume the `??` isnt working for you in this scenario? `x?.CenterName ?? ""` – David Pilkington Sep 10 '19 at 04:31
-
I have added it as an answer – David Pilkington Sep 10 '19 at 05:39
2 Answers
1
You can use the null-coalescing operator
x?.CenterName ?? string.Empty

aloisdg
- 22,270
- 6
- 85
- 105

David Pilkington
- 13,528
- 3
- 41
- 73
-1
You can implement C# ternary (? :) Operator. The syntax of ternary operator is:
Condition ? Expression1 : Expression2;
The Expressions below first checks for null conditions and if the condition is null, the value is set to empty.
return results.Select(x => new {
VillageName = x.VillageName,
GroupID = x.GroupID,
GroupName = x.GroupName == null ? "" : x.GroupName,
CenterID = x.CenterID,
CenterName = x.CenterName == null ? "" : x.CenterName,
}).ToList<object>();
or else you can use "The null-coalescing operator(??)" like:
CenterName = x.CenterName ?? "", //check and returns empty string if CenterName is null

anil shrestha
- 2,136
- 2
- 12
- 26
-
This code works well. I am even applying same method but how come people down vote my answer without even analyzing and testing it. Addition of comment for down vote with your reason would be greater. And yes this code works well. – anil shrestha Sep 10 '19 at 05:53