Check if collection is empty or not

Viewed 61161
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.

6 Answers

This worked for me in Dot Net Core but only for IEnumerable of Models not Entities (I got a bit of help from AutoMapper)

Cast it as a List then check the Capacity

IEnumerable<vwPOD_Master> podMasters = _podRepository.GetNewPods(PartNumber);

IEnumerable<NewPODsDTO> podList = Mapper.Map<IEnumerable<NewPODsDTO>>(podMasters);

if (((List<NewPODsDTO>)podList).Capacity == 0) {
    return NotFound(); 
}
Related