如何检查列表是否包含C#中的指定元素
要检查List是否包含指定的元素,代码如下-
示例
using System;using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<string> list1 = new List<string>();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("Elements in List1...");
foreach (string res in list1){
Console.WriteLine(res);
}
List<string> list2 = new List<string>();
list2.Add("India");
list2.Add("US");
list2.Add("UK");
list2.Add("Canada");
list2.Add("Poland");
list2.Add("Netherlands");
Console.WriteLine("Elements in List2...");
List<string>.Enumerator demoEnum = list2.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("Is List2 equal to List1? = "+list2.Equals(list1));
Console.Write("Does List2 has element Canada? = "+list2.Contains("Canada"));
}
}
输出结果
这将产生以下输出-
Elements in List1...One
Two
Three
Four
Five
Elements in List2...
India
US
UK
Canada
Poland
Netherlands
Is List2 equal to List1? = False Does List2 has element Canada? = True
示例
现在让我们来看另一个示例-
using System;using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
list.Add(500);
list.Add(600);
list.Add(700);
list.Add(800);
list.Add(900);
list.Add(1000);
Console.WriteLine("Elements in List...");
foreach (int res in list){
Console.WriteLine(res);
}
Console.Write("Does List has element 150? = "+list.Contains(150));
}
}
输出结果
这将产生以下输出-
Elements in List...100
200
300
400
500
600
700
800
900
1000
Does List has element 150? = False
以上是 如何检查列表是否包含C#中的指定元素 的全部内容, 来源链接: utcz.com/z/316150.html