0

感觉这里完全是个笨蛋。我有一个父对象,其中包含一周中每一天的子对象集合。所以我可以做类似的parent.MondayChildren事情parent.TuesdayChildren

我有一个父对象的集合,并且在我想要使用的 linq 查询中,parents.SelectMany(c => c.MondayChildren)但基于一周中的当前日期。

如何为SelectMany方法提供变量?

更新信息:

我现在看到我错过了重要信息。此查询将被转换为 SQL。解释一下,Units 由多个 SlotPools 组成,并且 PatientSchedules 被分配到一周中的每一天的 slotpool。

我的代码低于导致内部 .NET Framework 数据提供程序错误 1025。

Func<SlotPool, IEnumerable<PatientSchedule>> queryDay = null;

            switch (DateTime.Today.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    queryDay = d => d.MondayPatientSchedules;
                    break;
                case DayOfWeek.Tuesday:
                    queryDay = d => d.TuesdayPatientSchedules;
                    break;
                // .. Not shown for brevity
                default:
                    throw new NotSupportedException("Unsupported DayOfWeek");
            }    

IEnumerable<UnitWithCountVM> data = _unitOfWork.Units.GetAll()
                .Select(u => new UnitWithCountVM()
                {
                    ID = u.ID,
                    Name = u.Name,
                    PatientNumber = u.SlotPools.SelectMany(queryDay).Count()
                }).ToList();    
4

2 回答 2

0

也许有一个switch

List<Children> todaysChildren = parents
    .SelectMany(p =>
    {
        switch(DateTime.Today.DayOfWeek)
        {
            case DayOfWeek.Monday:
                return p.MondayChildren; 
            case DayOfWeek.Tuesday:
                return p.TuesdayChildren; 
            // ...
            default: 
                throw new NotSupportedException("Unsupported DayOfWeek");
        }
    })
    .ToList();
于 2013-11-14T13:10:42.483 回答
0

这是我的最终解决方案。关键是要提供一个表达式,还要将 .AsQueryable() 添加到我的 SlotPools 集合中。如果有人看到我可能错过的问题,请告诉我。我对 EntityFramework 和 Linq 很陌生:

Expression<Func<SlotPool, IEnumerable<PatientSchedule>>> queryDay = null;


        switch (DateTime.Today.DayOfWeek)
        {
            case DayOfWeek.Monday:
                queryDay = d => d.MondayPatientSchedules;
                break;
            case DayOfWeek.Thursday:
                queryDay = d => d.MondayPatientSchedules;
                break;
            // .. Not shown for brevity
            default:
                throw new NotSupportedException("Unsupported DayOfWeek");
        }

        IEnumerable<UnitWithCountVM> data = _unitOfWork.Units.GetAll()
            .OrderBy(u => u.Name)
            .Select(u => new UnitWithCountVM()
            {
                ID = u.ID,
                Name = u.Name,
                PatientNumber = u.SlotPools.AsQueryable().SelectMany(queryDay).Count()
            }).ToList();
于 2013-11-15T08:57:53.670 回答