3

I have the following class:

public class MyClass
{
        public DateTime? Date1 { get; set; }

        public DateTime? Date2 { get; set; }
}

Objects from this class always have one of those dates in null, and the other with a value, for example:

var obj1 = new MyClass
{
         Date1 = new DateTime(2020/12/12),
         Date2 = null
};
var obj2 = new MyClass
{
         Date1 = null,
         Date2 = new DateTime(2020/12/8)
};
var obj3 = new MyClass
{
         Date1 = new DateTime(2020/12/24)
         Date2 = null
};

Is there a way in which i can get the ordered data from my database context by those two properties? (Probably merging the two columns while doing the query, but then i don't want the output to have that merged column)

In this case the query should give the following result: [obj2, obj1, obj3]

  • 1
    Can you not do `.OrderBy(x => x.Date2 ?? x.Date1)`? I feel like EF should be able to translate that. From what I'm reading, EF can handle the null coalesce operator. – Jonesopolis Jan 05 '21 at 15:25
  • 1
    [Null coalesce not working in LINQ query](https://stackoverflow.com/q/11594275/3744182) and [Null coalescing operator not working in Entity Framework 6](https://stackoverflow.com/q/38934509/3744182) say that the null coalescing operator doesn't work in EF - but those are all quite old. If `??` doesn't work, `.OrderBy(x => x.Date1.HasValue ? x.Date1.Value : x.Date2.Value)` presumably should. – dbc Jan 05 '21 at 15:31

1 Answers1

3

If the above need to be just solved using Linq to Entities:

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
    public static void Main()
    {
        var obj1 = new MyClass
        {
            Date1 = new DateTime(2020,12,12),
            Date2 = null
        };
        var obj2 = new MyClass
        {
            Date1 = null,
            Date2 = new DateTime(2020,12,8)
        };
        var obj3 = new MyClass
        {
            Date1 = new DateTime(2020,12,2),
            Date2 = null
        };

        List<MyClass> lm = new List<MyClass>();
        lm.Add(obj1);
        lm.Add(obj2);
        lm.Add(obj3);
    
        var ls = lm.OrderBy(l => l.Date1 ?? l.Date2).ToList();
    
        ls.ForEach(s => Console.WriteLine(s.Date1 ?? s.Date2));
    }
}

public class MyClass
{
     public DateTime? Date1 { get; set; }
     public DateTime? Date2 { get; set; }
}

12/2/2020 12:00:00 AM
12/8/2020 12:00:00 AM
12/12/2020 12:00:00 AM

If you require to do this on a database using Linq to SQL, then you can use NOTMAPPED attribute in your Table class.

[NotMapped]
public int Date3 { get { return this.Date1??this.Date2; }  }

Then apply .OrderBy on this column.

Sunil
  • 3,404
  • 10
  • 23
  • 31