如何用LINQ执行这种不同的操作

本文关键字:操作 何用 LINQ 执行 | 更新日期: 2023-09-27 18:10:52

我有以下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
                };

但是现在我被产生不同的workingjournal的比较所困住了。
我有一种感觉,组按子句应该在这里,但我不确定它应该怎么做。

如何用LINQ执行这种不同的操作

假设LINQ对象:

(from workRoster in workRosters
 select new WorkingJournal
            {
                ServicePlan = workRoster.ServicePlan,
                Nurse = workRoster.Nurse,
                Month = workRoster.Start.Month,
                Year = workRoster.Start.Year
            }).Distinct();

注意,要使其工作,您需要为WorkingJournal对象实现EqualsGetHashCode。如果没有,请参阅Anthony的回答:如何使用LINQ执行这种Distinct操作?


如果是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;

如果在你的类中有适当的EqualsGetHashCode实现,你可以简单地调用Distinct()

var result = workRosters.Select(...).Distinct();
如果您没有这样的实现,您可以定义一个IEqualityComparer<WorkingJournal>实现。这将使您为T定义EqualsGetHashCode方法,然后可以由字典或哈希集使用,也可以在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);