比较C#ASP.NET MVC LINQ实体框架中的两个列表

本文关键字:列表 两个 NET C#ASP MVC LINQ 框架 实体 比较 | 更新日期: 2023-09-27 18:25:24

正如标题所说,我试图比较戳入日期时间和戳出日期时间。

我有一个弹性变量,它将得到一个工作日(8小时)中这两个日期之间的差值。

"如果我在08:00盖章,在17:00盖章,我的弹性应为+1(h)"

型号:

public class FlexModel
{
    public List<User> Users { get; set; }
    public List<Stamping> Stampings { get; set; } 
    public decimal FlexTime { get; set; }
}
public partial class Stamping
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public int UserId { get; set; }
    [Required]
    [DataType(DataType.DateTime)]
    public DateTime Timestamp { get; set; }
    [Required]
    [StringLength(3)]
    public string StampingType { get; set; }
    public virtual User User { get; set; }
}

视图:

@Html.LabelFor(model => model.FlexTime, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.DisplayFor(model => model.FlexTime, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.FlexTime, "", new { @class = "text-danger" })
</div>

控制器:

public ActionResult Info()
{
    var flexModel = new FlexModel();
    var userId = (int)Session["userId"];
    var user = _db.Users.Find(userId);
    var stampIn = _db.Stampings
                     .Where(i => i.StampingType == "in")
                     .Where(i => i.User == user)
                     .ToList();
    var stampOut = _db.Stampings
                      .Where(i => i.StampingType == "out")
                      .Where(i => i.User == user)
                      .ToList();
    var workDay = 8;
    if (stampIn.Count == 0)
    {
        return View();
    }
    foreach (var itemIn in stampIn)
    {
        //Dont know what to do here
    }
    foreach (var itemOut in stampOut)
    {
        //Dont know what to do here either
    }
    return View();
}

请帮忙。

比较C#ASP.NET MVC LINQ实体框架中的两个列表

您可以关联如下列表:

var attendance = from sin in stampIn
                 select new 
                 {
                    StampIn = sin,
                    StampOut = stampOut.FirstOrDefault(sout => 
                                    sout.Timestamp > sin.Timestamp)
                 };

这会给你一个stampin与stampout事件的列表(尽管stampout可能为null)。然后你需要这样计算弹性时间:

var flexitime = from att in attendance
                select new
                {
                    TimeIn = att.StampIn.Timestamp,
                    TimeOut = att.StampOut == null ? (DateTime?)null : att.StampOut.Timestamp,
                    TotalTime = att.StampOut == null ? 0 :  
                        att.StampOut.Timestamp.Subtract(att.StampIn.Timestamp).TotalHours
                };

您现在可以将其转换为FlexModel对象(我只填写FlexTime属性,因为我不确定您如何/为什么需要其他属性):

var workDay = 8;
var flexModel = new FlexModel 
{
    FlexTime = Convert.ToDecimal(flexitime
                   .Sum(f => f.TotalTime - workDay))
};
return View(flexModel);