C#从LINQ计算对象初始化期间的日期时间差异

时间:2017-04-12 13:03:31

标签: c# linq datetime

我有以下代码正常运行,它从SQL表中返回数据:

    List<TypeA> Class1 = ( from rec in Entity.Context.Table  select new Class1
                      { NAME = rec.name,
                        FIRSTDATE = rec.firstdate,
                        LASTDATE = rec.lastdate

                         //my func CalcTimeDiff, doesnt work
                          ElapsedMin = CalcTimeDiff(LASTDATE, FIRSTDATE) 

                       }).ToList();
public class Class1
{
   public string  NAME = {get; set;}
   public Nullable<DateTime> FIRSTDATE = {get; set;}
   public Nullable<DateTime> LASTDATE = {get; set;}
   public int ElapsedMin = {get; set;}

   // My function to calculate time difference
    public int CalcTimeDiff ( DateTime A, DateTime B)
          {
              TimeSpan Diff = A - B;
              int MinElapsed = (int)Diff.TotalMinutes;
              return MinElapsed;
            }
}

我正在寻找的是添加方法来计算LASTDATE和FIRSTDATE之间的DateTime差异到Class1类并在Class1初始化中调用它。但仍然没有运气,得到错误我不能使用非静态字段......任何想法如何管理?

3 个答案:

答案 0 :(得分:5)

除非您需要设置ElapsedMin(我无法理解您的原因),否则请将其设为计算属性:

public int ElapsedMin => CalcTimeDiff(FirstDate, LastDate);

public int ElapsedMin => (int)(LastDate - FirstDate).Value.TotalMinutes;

答案 1 :(得分:0)

我认为你正在寻找类似的东西。

public class Class1
{
    public string NAME { get; set; }

    public Nullable<DateTime> FIRSTDATE { get; set; }

    public Nullable<DateTime> LASTDATE { get; set; }

    public int ElapsedMin { get; set; }


    public Class1(DateTime LD, DateTime FD)
    {
        TimeSpan Diff = LD - FD;
        this.ElapsedMin = (int)Diff.TotalMinutes;
    }

}

公共类Class2

{

    public void Test()

    {

        Class1 c1 = new Class1(DateTime.Now ,Convert.ToDateTime("01-23-1992"));
        int elapsedMin = c1.ElapsedMin;

    }
}

答案 2 :(得分:-1)

你做的事情有点乱。小心机智。

var resultList = (from rec
                      in recordList
                      select new Class1
                      {
                          NAME = rec.name,
                          FIRSTDATE = rec.firstdate,
                          LASTDATE = rec.lastdate,
                          ElapsedMin = (int)(rec.lastdate.Value  - rec.firstdate.Value).TotalMinutes
                      }).ToList();