C#: Return any item that matches the condition

戏子无情 提交于 2019-12-25 04:09:40

问题


I have a method like this:

    public ActionResult ShowAvailableSpots(int Id, DateTime ArrivalDate, DateTime LeaveDate)
    {
        var query2 = db.Spots
            .Where(c => db.Reservations.Any(r =>
                           DbFunctions.TruncateTime(ArrivalDate) <= DbFunctions.TruncateTime(r.ArrivalDate) && DbFunctions.TruncateTime(LeaveDate) <= DbFunctions.TruncateTime(r.ArrivalDate)
                        || DbFunctions.TruncateTime(ArrivalDate) >= DbFunctions.TruncateTime(r.LeaveDate)
            )).ToList();

        ViewBag.StartingDate = ArrivalDate;
        ViewBag.EndingDate = LeaveDate;
        ViewBag.AvailableSpots = query2;

        ViewBag.CampingSpotId = new SelectList(query2, "CampingSpotId", "SpotName");

        return View();
    }

It determines wether any of the reservations match the date criteria. If they don't match, then the list with Campingspots is returned.

The problem is, that it is returning ALL spots or NONE spots instead of just the spots that are available. This is due to the .Any method. How can I filter out the campingspots that are not available?


回答1:


Try something like this:

var query2 = db.Spots.Where(c => db.Reservations
                                   .Where(r => c.CampingSpotId == r.CampingSpotId)
                                   .All(r => DbFunctions.TruncateTime(LeaveDate) <= DbFunctions.TruncateTime(r.ArrivalDate)
                                          || DbFunctions.TruncateTime(ArrivalDate) >= DbFunctions.TruncateTime(r.LeaveDate))
                   )).ToList();

The inner Where statement says we're only checking the reservations that apply to that camping spot, and the All statement checks to make sure that every reservation for that campsite is outside the window we're interested in.



来源:https://stackoverflow.com/questions/28905393/c-return-any-item-that-matches-the-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!