Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my Linq select return values if the value selected is null?

Tags:

c#

linq

I have the following code:

    [DisplayName("Created")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? Created { get; set; }

    [DisplayName("Modified By")]
    public string ModifiedBy { get; set; }

    [DisplayName("Modified")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? Modified { get; set; }

        from d in data
        select new Content.Grid
        {
            PartitionKey = d.PartitionKey,
            RowKey = d.RowKey,
            Order = d.Order,
            Title = d.Title,e
            Created = d.Created,
            CreatedBy = d.CreatedBy,
            Modified = d.Modified,
            ModifiedBy = d.ModifiedBy
        };

There is a possibility that d.Created, d.CreatedBy, d.Modified and d.ModifiedBy may be null.

How can I make it so that if they are null then the select returns n/a for the CreatedBy and ModifiedBy and returns the date January, 1, 2012 for the Created and Modified?

like image 823
Alan2 Avatar asked Aug 19 '12 06:08

Alan2


People also ask

Can LINQ Select return null?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer.

Can ToList () return null?

If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.

Is null SQL in LINQ?

NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false". Save this answer.

Is null in LINQ C#?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.


1 Answers

You can use the null-coalescing operator (??) to give default values for nullable value types or reference types:

from d in data
select new Content.Grid
{
    PartitionKey = d.PartitionKey,
    RowKey = d.RowKey,
    Order = d.Order,
    Title = d.Title,e
    Created = d.Created ?? new DateTime(2012,1,1),
    CreatedBy = d.CreatedBy ?? "n/a",
    Modified = d.Modified ?? new DateTime(2012,1,1),
    ModifiedBy = d.ModifiedBy ?? "n/a"
};
like image 70
nemesv Avatar answered Oct 13 '22 03:10

nemesv