-1
return results.Select(x => new {                
            VillageName = x.VillageName,
            GroupID = x.GroupID,
            GroupName = x.GroupName,
            CenterID = x.CenterID,
            CenterName = x.CenterName,
        }).ToList<object>();
David Pilkington
  • 13,528
  • 3
  • 41
  • 73

2 Answers2

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