如何将变量传递给.SelectMany

时间:2013-11-14 12:58:44

标签: c# entity-framework linq

感觉就像这里的笨蛋一样。我有一个父对象,它包含一周中每一天的子对象集合。所以我可以做parent.MondayChildrenparent.TuesdayChildren等等。

我有一组父对象,在我的linq查询中,我想使用parents.SelectMany(c => c.MondayChildren)但是基于当周的当天。

如何为SelectMany方法提供变量?

更新信息:

我现在看到我已经错过了重要信息。此查询将转换为SQL。为了解释,单位由多个SlotPools组成,PatientSchedules被分配到一周的每一天的一个槽池。

我的代码位于下面,导致内部.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();    

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

这是我的最终解决方案。关键是要提供一个Expression,还要将.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();