-1
return results.Select(x => new {                
            VillageName = x.VillageName,
            GroupID = x.GroupID,
            GroupName = x.GroupName,
            CenterID = x.CenterID,
            CenterName = x.CenterName,
        }).ToList<object>();
3
  • if CenterName and group name is null. Need to return an empty string In c# 6.0, x?.CenterName -> return null value Commented Sep 10, 2019 at 4:28
  • 1
    I assume the ?? isnt working for you in this scenario? x?.CenterName ?? "" Commented Sep 10, 2019 at 4:31
  • I have added it as an answer Commented Sep 10, 2019 at 5:39

2 Answers 2

1

You can use the null-coalescing operator

x?.CenterName ?? string.Empty
Sign up to request clarification or add additional context in comments.

Comments

-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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.