Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq replace null/empty value with another value

In sql server I create views where I can check for null values and replace them with a default if I want (i.e. ISNULL(PrimaryPhone, 'No Primary #') AS PrimaryPhone. I used a lot of views in my asp.net web forms application, but I am now learning MVC 4 and want to start out right.

I have a model, controller and view set up for my client table. I would like to be able to replace null/empty values with ("Not Entered") or something like that. I believe this needs to go in the controller, please correct me if I'm wrong.

I saw an example that uses hasvalue, but it is not available through intellisense.

How would I replace empty/null values without using DefaultValue in my model?

Thanks

var result = db.Clients.Select(x => new
        {
            CustomerID = x.CustomerID,
            UserID = x.UserID,
            FullName = x.FullName,
            EmailAdd = x.emailadd.DefaultIfEmpty("No Email"),....
like image 768
Sheri Trager Avatar asked Dec 15 '12 18:12

Sheri Trager


1 Answers

You can use the ?? operator to set a default value when something is null:

var result = db.Clients.Select(x => new
        {
            CustomerID = x.CustomerID,
            UserID = x.UserID,
            FullName = x.FullName,
            EmailAdd = x.emailadd ?? "No Email", ...

If you need more control, for example checking for both null and empty, you can also use the ?: operator (also known as the "conditional operator" or "ternary operator"):

var result = db.Clients.Select(x => new
        {
            CustomerID = x.CustomerID,
            UserID = x.UserID,
            FullName = x.FullName,
            EmailAdd = string.IsNullOrEmpty(x.emailadd) ? "No Email" : x.emailadd, ...
like image 175
Scott Chapman Avatar answered Oct 16 '22 06:10

Scott Chapman