Make sure the collection is empty or not.

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 foreach in an if statement, which checks

 var devices = collection["devices"]; 

empty or not. If its empty for each should not be executed. For the record, the ["devices"] collection is a set of checkbox values ​​from the form.

+6
collections c # asp.net-mvc
source share
5 answers

You do not need to check if the collection is empty, if it is empty, the code inside ForEach will not be executed, see my example below.

 using System; using System.Collections.Generic; namespace Test { class Program { static void Main(string[] args) { List<string> emptyList = new List<string>(); foreach (string item in emptyList) { Console.WriteLine("This will not be printed"); } List<string> list = new List<string>(); list.Add("item 1"); list.Add("item 2"); foreach (string item in list) { Console.WriteLine(item); } Console.ReadLine(); } } } 
+6
source share

You can use the Count field to check if the collection is empty or not.

so you get something like this:

 if(devices.Count > 0) { //foreach loop } 
+13
source share

You can use the Any method to find out if a collection is like any element.

 if (devices.Any()) { //devices is not empty } 
+5
source share

Your code, as it is, will not work, since you say that collection["devices"] is a set of flag values, and yet you drop it to string . Do you mean collection flag value? What is the exact type of collection ?

Any object that implements ICollection or ICollection<T> can be checked to see if it is empty or not if the Count property is greater than zero.

+1
source share

How about checking the length of the array

 if (arr2.length > 0) { foreach (int i in arr2) { Device d = Device.Find(i); d.Projects.Add(project); d.SaveAndFlush(); } } 
0
source share