在用户类型列表列表中查找常见项目



我有一个 studyTimeList 包含 ScheduleStudyTime 列表 - 我的用户类型。我试图在列表中找到一个共同的ScheduleStudyTime。这是我的代码:

private class ScheduleStudyTime
{
public int STUDTIME_ID { get; set; }
public int DAY_ID { get; set; }
public int LESSTIME_ID { get; set; }
public int SCHOOLYEAR_ID { get; set; }
}
private void LoadStudyTime()
{
var fourths = dbContext.FOURTH.Where(x => x.CHOOSE_SCHEDULE_FOURTH.Any(a => a.SCHEDVARIANT_ID == ScheduleVariant.SCHEDVARIANT_ID)).ToList();
int fourthCount = fourths != null ? fourths.Count() : 0;
List<ScheduleStudyTime>[] studyTimeList = new List<ScheduleStudyTime>[fourthCount];
for (int i = 0; i <= (fourthCount - 1); ++i)
{
int fourthId = fourths[i].FOURTH_ID;
var chooseStudyTime = from CHOOSE_STUDY_FOURTH in dbContext.CHOOSE_STUDY_FOURTH
where CHOOSE_STUDY_FOURTH.STUDY_TIME.SCHOOLYEAR_ID == Properties.Settings.Default.SchoolYearId &&
CHOOSE_STUDY_FOURTH.FOURTH_ID == fourthId
group CHOOSE_STUDY_FOURTH by new
{
CHOOSE_STUDY_FOURTH.STUDY_TIME.STUDTIME_ID,
CHOOSE_STUDY_FOURTH.STUDY_TIME.DAY_ID,
CHOOSE_STUDY_FOURTH.STUDY_TIME.LESSTIME_ID,
CHOOSE_STUDY_FOURTH.STUDY_TIME.SCHOOLYEAR_ID
}
into gcsf
select new ScheduleStudyTime
{
STUDTIME_ID = gcsf.Key.STUDTIME_ID,
DAY_ID = gcsf.Key.DAY_ID,
LESSTIME_ID = gcsf.Key.LESSTIME_ID,
SCHOOLYEAR_ID = gcsf.Key.SCHOOLYEAR_ID
};
studyTimeList[i] = chooseStudyTime.ToList();
}
var commonStudyTime = studyTimeList.Aggregate((xs, ys) => xs.Intersect(ys).ToList());
}

如果 commonStudyTime 返回零,即使有匹配项,我该怎么做

Intersect方法将使用默认比较器,该比较器基本上检查(对于引用类型(引用是否相同。由于列表具有object类型,并且它们是不同的对象,因此它将返回 0 个结果。

要做你想做的事情,你必须告诉Intersect方法如何进行比较检查。所以你需要这样的东西:

public class ScheduleStudyTimeComparer : IEqualityComparer<ScheduleStudyTime>
{
public bool Equals(ScheduleStudyTime x, ScheduleStudyTime y)
{
// TODO: Check for nulls and possibly make the decision using
// other properties as well
return x.STUDTIME_ID  == y.STUDTIME_ID ;
}
public int GetHashCode(ScheduleStudyTime obj)
{
return obj.ScheduleStudyTime.GetHashCode();
}
}

现在告诉Intersect方法使用它:

xs.Intersect(ys, new ScheduleStudyTimeComparer())

相关内容

最新更新