【问题标题】:c# how to see which variable that is in the same index as another variable in another listc#如何查看与另一个列表中的另一个变量在同一索引中的哪个变量
【发布时间】:2020-07-26 18:52:39
【问题描述】:

示例:

List<string> myList1 = new List<string>();
List<string> myList2 = new List<string>();

myList1.Add("hello1");
myList1.Add("hello2");

myList2.Add("hello3");
myList2.Add("hello1");

我的问题是如何让程序返回与该变量在同一索引中的同一变量。例如:如果我从 list1 中选择 hello1,它应该返回相同索引中的变量,在这种情况下是 hello3。如果您有任何问题或不明白我在说什么,请写。

【问题讨论】:

标签: c# list indexing


【解决方案1】:
int index = myList1.FindIndex(a => a == "hello1");
string otherItem = myList2[index];

您可以使用 FindIndex() 方法查找索引,然后从另一个列表中获取该索引处的字符串。

希望这会有所帮助。

【讨论】:

  • 嗨,感谢您的帮助!我的问题是 mylist2 持有对象。然后我得到错误:不能将类型'string'隐式转换为'int'。你能帮我解决这个问题吗?
  • @edwardthecoder 你能告诉我 list2 和 list1 到底包含什么
  • 当然!列表 2 包含对象,该类包含两个字符串,用户名和密码。在这里,当我尝试查看哪个对象与字符串“index”在同一索引中时,它显示错误:无法将类型“string”隐式转换为“int”。
  • @edwardthecoder 我认为您只需将string 更改为您拥有的对象的名称。试试看。如果它不起作用,请告诉我。
  • 您好!有效。我在“otherItem”前面添加了对象,因为它变成了一个对象并且它起作用了。唯一的问题是我无法访问类中的字符串(用户名和密码)。我不能这样写:otherItem.username 或 otherItem.password。
猜你喜欢
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
相关资源
最近更新 更多