C#在数组中使用 foreach 循环
让我们看一个在数组中使用foreach循环的示例-
示例
using System; public class Demo { public static void Main() { string[] products = new string[] { "Electronics", "Accessories", "Clothing", "Toys", "Clothing", "Furniture" }; Console.WriteLine("Products 列表..."); foreach(string s in products) { Console.WriteLine(s); } Console.WriteLine("Accessories 是否在数组 products 中? = {0}", Array.Exists(products, ele => ele == "Accessories")); Console.WriteLine("Stationery 是否在数组 products 中? = {0}", Array.Exists(products, ele => ele == "Stationery")); Console.WriteLine("\products 数组有一个或多个元素以字母 C 开头? = {0}", Array.Exists(products, ele => ele.StartsWith("C"))); Console.WriteLine("products 数组有一个或多个元素以字母 D 开头? = {0}", Array.Exists(products, ele => ele.StartsWith("D"))); Console.WriteLine("products 数组有一个或多个元素以字母 T 开头? = {0}", Array.Exists(products, ele => ele.StartsWith("T"))); Console.WriteLine("products 数组有一个或多个元素以字母 E 开头? = {0}", Array.Exists(products, ele => ele.StartsWith("E"))); Console.WriteLine("数组的大小是否固定e? = " + products.IsFixedSize); } }
输出结果
这将产生以下输出-
Products list... Electronics Accessories Clothing Toys Clothing Furniture Accessories 是否在数组 products 中? = True Stationery 是否在数组 products 中? = False products 数组有一个或多个元素以字母 C 开头? = True products 数组有一个或多个元素以字母 D 开头'? = False products 数组有一个或多个元素以字母 T 开头? = True products 数组有一个或多个元素以字母 E 开头? = True 数组的大小是否固定? = True
示例
让我们看另一个例子-
using System; public class Demo { public static void Main() { String[] strArr1 = new String[3] { "John", "Jacob", "Tim"}; String[] strArr2 = new String[3] { "Tom","Brad","Bradley"}; Console.WriteLine("第一个字符串数组..."); foreach(string val in strArr1) { Console.WriteLine(val); } Console.WriteLine("第二个字符串数组..."); foreach(string val in strArr2) { Console.WriteLine(val); } Console.WriteLine("两个数组对象是否相等? = "+strArr1.Equals(strArr2)); } }
输出结果
这将产生以下输出-
第一个字符串数组... John Jacob Tim 第二个字符串数组... Tom Brad Bradley 两个数组对象是否相等? = False