首页 > 解决方案 > 从两个数组对象中获取不匹配的数组

问题描述

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {

        string Card = (Request.Params["Card"]);
        DateTime Date = DateTime.Parse(Request.Params["Date"]);

        using ( AttendanceContext db = new AttendanceContext())
        {
            lblEmpName.Text = db.users.Where(t => t.Card == Card).SingleOrDefault().EmployeeName;
            lblDate.Text = Date.ToString("dd/MM/yyyy");
            if (lblEmpName.Text == null)
            {
                lblEmpName.Text = "No Data";
            }
            if (lblDate.Text == null)
            {
                lblDate.Text = "No Date";
            }

            var firstArray = db.TimeoutJustification.Where(x => x.Date == Date && x.Card == Card && x.GeneralJustification != null).ToList();

            var SecondArray = GetTimeOutData(Card, Date).OrderByDescending(t => t.Date).ToList();

            ///This is where i need to check both arrays
            var filtered = firstArray.Except(SecondArray);
            //var d = newTimeoutdata.Where(t => !newTimeoutdata.Contains(t.TimeOut.ToString())).ToList();
            if(filtered!=null){
                //This is where i will insert the unmatched array
                db.TimeoutJustification.AddRange(filtered);
                db.SaveChanges();
            }
        }

    }
}
}

我的第一个数组包含 3 个项目,这些项目与我的第二个数组中的 3 个项目相同。

我只需要从我的第二个数组中获取第 4 个不匹配的项目。请记住,我需要比较两个数组,datetime TimeOut因为日期和卡片在所有数组中总是相同的

标签: c#.netentity-frameworklinq

解决方案


您可以使用该Except方法,如下所示:

secondArray.Except(firstArray)

但是,您可能还需要为此目的使用自定义相等比较器。我不确定您在班级中的属性,例如,您可以执行以下操作:

public class DistinctItemComparer : IEqualityComparer<yourClass>
{

    public bool Equals(yourClass x, yourClass y)
    {
        return x.Id == y.Id &&
            x.Date == y.Date &&
            x.Card == y.Card;
    }

    public int GetHashCode(yourClass obj)
    {
        return obj.Id.GetHashCode() ^
            obj.Date.GetHashCode() ^
            obj.Card.GetHashCode();
    }
}

然后像这样使用它:

secondArray.Except(firstArray, new DistinctItemComparer())

推荐阅读