public ActionResult Create(FormCollection collection, FormCollection formValue)
{
try
{
Project project = new Project();
TryUpdateModel(project, _updateableFields);
var devices = collection["devices"];
string[] arr1 = ((string)devices).Split(',');
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));
project.User = SessionVariables.AuthenticatedUser;
var time = formValue["Date"];
project.Date = time;
project.SaveAndFlush();
foreach (int i in arr2)
{
Device d = Device.Find(i);
d.Projects.Add(project);
d.SaveAndFlush();
}
return RedirectToAction("Index");
}
catch (Exception e)
{
return View(e);
}
}
I want to wrap the foreach in a if statement which checks if
var devices = collection["devices"];
is empty or not. If its empty the for each should not be executed. For the record, collection["devices"] is a collection of checkbox values from a form.
The size() and isEmpty() of java. util. Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value.
isEmpty() doesn't check if a list is null . If you are using the Spring framework you can use the CollectionUtils class to check if a list is empty or not.
You can use the Count
field to check if the collection is empty or not
so you will end up with something like this :
if(devices.Count > 0)
{
//foreach loop
}
You can use the method Any
to know if a collection as any element.
if (devices.Any())
{
//devices is not empty
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With