简体   繁体   中英

How to check in a variable contains a specific string c#?

I have a variable that after querying the database it returns back a set of rows. Each row has an item id plus start date and end date .

I am trying to use this variable so if the input from my application matches any of these set of rows, the variable has returned to do something.

How can this be done? Currently my if statement is checking only the first row of what the variable has returned. I need it to check all the rows !

Here is the code from my controller :

var dateAvailability=from s in db.Bookings
                     where s.ItemId == id && s.StartDate < s.EndDate 
                           && s.EndDate > s.StartDate
                     select s;
 if (ModelState.IsValid)
 {
     foreach (var data in dateAvailability.ToList())
     {
        if (booking.ItemId == id && (StartDate == data.StartDate) && (EndDate == data.EndDate))
        {
             ViewBag.error = "Dates already exists";
        }
        else                 
            db.Bookings.Add(booking);
            db.SaveChanges();
        return RedirectToAction("Confirmation",
                                    new { id = booking.BookingId });

      }
 }

You can use Any :

bool dateExistsAlready = dateAvailability 
   .Any(d => booking.ItemId == id && StartDate == d.StartDate && EndDate == d.EndDate);
if(dateExistsAlready)
{
   ViewBag.error = "Dates already exists";
}
else
{
   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM