简体   繁体   English

有没有办法通过两个属性同时使用 LINQ

[英]Is there a way to orderBy two properties simultaneously using LINQ

I have the following class:我有以下 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:此 class 中的对象始终在 null 中具有这些日期之一,而另一个具有值,例如:

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) (可能在进行查询时合并两列,但是我不希望 output 具有该合并列)

In this case the query should give the following result: [obj2, obj1, obj3]在这种情况下,查询应该给出以下结果:[obj2, obj1, obj3]

If the above need to be just solved using Linq to Entities:如果上面需要使用 Linq 来解决实体:

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 2020 年 12 月 2 日上午 12:00:00
12/8/2020 12:00:00 AM 2020 年 12 月 8 日上午 12:00:00
12/12/2020 12:00:00 AM 2020 年 12 月 12 日上午 12:00:00

If you require to do this on a database using Linq to SQL, then you can use NOTMAPPED attribute in your Table class.如果您需要在使用 Linq 到 SQL 的数据库上执行此操作,则可以在表 class 中使用NOTMAPPED属性。

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

Then apply .OrderBy on this column.然后在此列上应用.OrderBy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM