检查两个列表中的索引是否相同C# [英] Check if indexes in two lists are the same C#
问题描述
我正在研究比较两个相同的索引。基本上我宣布两个名单。
我尝试过:
Hi,
I am working on comparing two same indexes. Basically I am declaring two lists.
What I have tried:
List<string> names = new List<string>() { "Bob", "Lara", "Andrew", "Adam" };
List<string> surnames = new List<string>() { "Dar", "Tars", "Vernik", "Smith" };
我正在生成随机的名字或姓氏并显示它:< br $>
and I am generating a random of either names or surnames and displaying it:
List<String> fullnames = names.Concat(surnames).ToList();
Random rand = new Random();
String randomname = fullnames[rand.Next(fullnames.Count)];
Console.WriteLine(randomname);
我想知道如何比较两者中的索引已经随机生成的列表。
例如下一个随机是名字Bob
所以如果
索引1个名字= bob
AND
指数1 in surnames = Dar
做点什么....
如果我正确理解了您的要求,那么任何帮助都会被认可
I was wondering how to compare an index in both of the lists that have been randomly generated.
For example next random is name Bob
So if
index 1 in names = bob
AND
index 1 in surnames = Dar
do something....
Any help would be apprciated
推荐答案
这样会有所帮助,我认为没有必要比较两个列表,数据总是不同。
if i understood your requirement correctly then this would help, and i think there is no point of comparing two lists, the data is always different.
List<string> names = new List<string>() { "Bob", "Lara", "Andrew", "Adam" };
List<string> surnames = new List<string>() { "Dar", "Tars", "Vernik", "Smith" };
List<String> fullnames = names.Concat(surnames).ToList();
Random rand = new Random();
String randomname = fullnames[rand.Next(fullnames.Count)];
int index = names.IndexOf(randomname); // check randomname is present in names list
if (index == -1) // not in names list
index = surnames.IndexOf(randomname); // index of the random name in the surnames list
string name = names[index]; // Bob
string surname = surnames[index];// Dar
无法正确理解你是怎么回事生成列表但是如果你想要在列表中获取不同的项目,那么使用类似下面的方法会有所帮助,我相信 -
Not correctly able to understand how/why you are generating the lists but having method something like following can help if you are trying to get the dissimilar items in the list, I believe-
public IEnumerable<string> GetDifferences(List<string> list1, List<string> list2)
{
for (int i = 0; i < list1.Count; i++)
{
if (list1[i] != list2[i]) yield return list1[i];
}
}
ref: c# - 比较两个List< string>按值和索引 - 堆栈溢出 [ ^ ] < br $> b $ b
根据您的要求,您可以在IF块中编写必要的逻辑,而不是返回项目。
希望,它有助于:)
ref: c# - Compare two List<string> by value and index - Stack Overflow[^]
According to your requirement, instead of returning the item, you can write the necessary logic in the IF block.
Hope, it helps :)
这篇关于检查两个列表中的索引是否相同C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!