检查某些列表值是否属于另一个列表
本文关键字:列表 属于 另一个 是否 检查 | 更新日期: 2023-09-27 18:01:29
我有两个单词列表
List<string> mainList = new List<string> {"blue", "green", "mother", "black", "gray"};
List<string> checkList = new List<string> {"mother", "green", "father", "black", "gray"};
然后我想从第一个列表中取一个随机元素…
Random rand = new Random();
string iGenerated = mainList[rand.Next(mainList.Count)];
和检查这个字符串是否也属于第二个列表。我不确定我到底该怎么做。我认为史密斯是这样的……这是正确的方式吗?
if checkList.Contains(iGenerated) bool strInArray = true;
else bool strInArray = false;
您尝试做的事情可以使用List
的Contains()
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> mainList = new List<string> { "blue", "green", "mother", "black", "gray" };
List<string> checkList = new List<string> { "mother", "green", "father", "black", "gray" };
Random r = new Random();
// Run five random tests
for (int i = 0; i < 5; i++)
{
string mainListItem = mainList[r.Next(0, mainList.Count)];
Console.WriteLine(checkList.Contains(mainListItem)
? "{0} found in checkList"
: "{0} not found in checkList", mainListItem);
}
}
}
结果:
green found in checkList
mother found in checkList
gray found in checkList
blue not found in checkList
mother found in checkList
演示这是我在控制台应用程序中的程序:
static void Main(string[] args)
{
List<string> color1 = new List<string> { "blue", "green", "mother", "black", "gray" };
List<string> color2 = new List<string> { "mother", "green", "father", "black", "gray" };
string rd = GetRandom(color1);
if (color2.Contains(rd))
{
// do something
Console.WriteLine(rd);
}
else
{
// do another work
}
Console.Read();
}
static string GetRandom(List<string> color)
{
var arr = color.ToArray();
Random rd=new Random();
int n = rd.Next(arr.Length);
return arr[n];
}