检查集合是否为空
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获得了一些帮助)
将其作为列表投射,然后检查容量
上述就是C#学习教程:检查集合是否为空分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
IEnumerable podMasters = _podRepository.GetNewPods(PartNumber); IEnumerable podList = Mapper.Map>(podMasters); if (((List )podList).Capacity == 0) { return NotFound(); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/952968.html