gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:31:19 25 4
gpt4 key购买 nike

下面的代码运行良好,它从 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 初始化时调用它。但仍然没有运气,出现错误我不能使用非静态字段......知道如何管理它吗?

最佳答案

除非你需要 ElapsedMin 是可设置的(我不明白你为什么要这样做),只需将它设为计算属性即可:

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

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

关于C# 从 LINQ 计算对象初始化期间的日期时间差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43370371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com