检查集合是否为空
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); } }
我想将foreach包装在if语句中,检查是否
var devices = collection["devices"];
是空的。 如果它为空,则不应执行每个。 对于记录,集合[“devices”]是表单中复选框值的集合。
您不需要检查集合是否为空,如果它是空的,ForEach中的代码将不会被执行,请参阅下面的示例。
using System; using System.Collections.Generic; namespace Test { class Program { static void Main(string[] args) { List emptyList = new List (); foreach (string item in emptyList) { Console.WriteLine("This will not be printed"); } List list = new List (); list.Add("item 1"); list.Add("item 2"); foreach (string item in list) { Console.WriteLine(item); } Console.ReadLine(); } } }
您可以使用“ Count
字段来检查集合是否为空
所以你最终得到这样的东西:
if(devices.Count > 0) { //foreach loop }
您可以使用方法Any
来了解集合是否为任何元素。
if (devices.Any()) { //devices is not empty }
你现在的代码不会起作用,正如你所说collection["devices"]
是一个复选框值的集合,然而你将它转换为string
。 你的意思是collection
是复选框值吗? collection
的确切类型是什么?
通过检查Count
属性是否大于零,可以检查实现ICollection
或ICollection
任何对象是否为空。
如何检查数组长度
if (arr2.length > 0) { foreach (int i in arr2) { Device d = Device.Find(i); d.Projects.Add(project); d.SaveAndFlush(); } }
这在Dot Net Core中适用于我,但仅适用于IEnumerable of Models而不是实体(我从AutoMapper获得了一些帮助)
将其作为列表投射,然后检查容量
IEnumerable podMasters = _podRepository.GetNewPods(PartNumber); IEnumerable podList = Mapper.Map>(podMasters); if (((List )podList).Capacity == 0) { return NotFound(); }
- 当前上下文中不存在名称“DefaultAuthenticationTypes”
- @ Html.DisplayText实际上不会显示文本
- 如何告诉Web API / Castle Windsor路由引擎在我的存储库中使用不同的数据库实例?
- entity framework自动生成GUID
- 有没有什么好的理由不在核心MVC中使用ViewComponent而不是Partial View?
- 如何在ASP .NET MVC中将对象列表与用户(Account)关联
- MVC @ Html.DropDownList在ViewBag中使用SelectList获取错误
- MVC中的十进制符号问题,C#?
- 将自定义HTML Helper添加到MVC项目