我有以下foreach
循环:
List<WorkingJournal> workingJournals = new List<WorkingJournal>();
foreach (WorkRoster workRoster in workRosters)
{
bool exists = workingJournals.Any(workingJournal => workingJournal.ServicePlan.Id == workRoster.ServicePlan.Id
&& workingJournal.Nurse.Id == workRoster.Nurse.Id
&& workingJournal.Month == workRoster.Start.Month
&& workingJournal.Year == workRoster.Start.Year);
if (exists == false)
{
WorkingJournal workingJournal = new WorkingJournal
{
ServicePlan = workRoster.ServicePlan,
Nurse = workRoster.Nurse,
Month = workRoster.Start.Month,
Year = workRoster.Start.Year
};
workingJournals.Add(workingJournal);
}
}
我开始写作:
from workRoster in workRosters
select new WorkingJournal
{
ServicePlan = workRoster.ServicePlan,
Nurse = workRoster.Nurse,
Month = workRoster.Start.Month,
Year = workRoster.Start.Year
};
但是现在我对产生不同工作日期的比较感到困惑 我觉得group by子句应该在这里,但我不确定应该怎么做。
答案 0 :(得分:3)
假设LINQ为对象:
(from workRoster in workRosters
select new WorkingJournal
{
ServicePlan = workRoster.ServicePlan,
Nurse = workRoster.Nurse,
Month = workRoster.Start.Month,
Year = workRoster.Start.Year
}).Distinct();
请注意,为了实现此功能,您需要为Equals
对象实施GetHashCode
和WorkingJournal
。如果没有,请参阅Anthony的回答:How to perform a this kind of Distinct operation with LINQ?
如果它是LINQ to SQL,您可以按新表达式分组,然后选择组密钥:
from workRoster in workRosters
group workRoster by new WorkingJournal
{
ServicePlan = workRoster.ServicePlan,
Nurse = workRoster.Nurse,
Month = workRoster.Start.Month,
Year = workRoster.Start.Year
} into workRosterGroup
select workRosterGroup.Key;
答案 1 :(得分:1)
如果您的课程中有适当的Equals
和GetHashCode
实施,您只需调用Distinct()
。
var result = workRosters.Select(...).Distinct();
如果没有这样的实现,您可以定义IEqualityComparer<WorkingJournal>
实现。这将使您为Equals
定义GetHashCode
和T
方法,然后可以由字典或哈希集使用,也可以在Linq中Distinct()
的重载中使用。
class JournalComparer : IEqualityComparer<WorkingJournal>
{
public bool Equals(WorkingJournal left, WorkingJournal right)
{
// perform your equality semantics here
}
public int GetHashCode(WorkingJournal obj)
{
// return some hash code here.
return obj.ServicePlan.GetHashCode();
}
}
var comparer = new JournalComparer(); // implements the interface
var result = workRosters.Select(r => new WorkingJournal { ... }).Distinct(comparer);