c#如何查看与另一个列表中的另一个变量位于同一索引中的哪个变量
例如:c#如何查看与另一个列表中的另一个变量位于同一索引中的哪个变量,c#,list,indexing,C#,List,Indexing,例如: List<string> myList1 = new List<string>(); List<string> myList2 = new List<string>(); myList1.Add("hello1"); myList1.Add("hello2"); myList2.Add("hello3"); myList2.Add("hello1"); L
List<string> myList1 = new List<string>();
List<string> myList2 = new List<string>();
myList1.Add("hello1");
myList1.Add("hello2");
myList2.Add("hello3");
myList2.Add("hello1");
List myList1=new List();
List myList2=新列表();
myList1.添加(“hello1”);
myList1.添加(“hello2”);
myList2.添加(“hello3”);
myList2.添加(“hello1”);
我的问题是如何让程序返回与该变量位于同一索引中的同一变量。例如:如果我从列表1中选择hello1,它应该返回同一索引中的变量,在这种情况下为hello3。如果你有任何问题或不明白我在说什么,请写信
int index = myList1.FindIndex(a => a == "hello1");
string otherItem = myList2[index];
可以使用FindIndex()方法查找索引,然后从另一个列表中获取该索引处的字符串
希望这有帮助。建议阅读:嗨,谢谢你的帮助!我的问题是mylist2保存对象。然后我得到错误:无法隐式地将类型“string”转换为“int”。你能帮我做这个吗?@Edward编码员:当然,你能给我看看列表2和列表1到底包含什么吗?当然!列表2包含对象,该类包含两个字符串:用户名和密码。这里,当我尝试查看哪个对象与字符串“index”位于同一索引中时,它显示了错误:无法将类型“string”隐式转换为“int”。@edwardthecoder我认为您只需要将
string
更改为您拥有的对象的名称。试试看。如果不起作用,请告诉我。你好!成功了。我在“otherItem”前面添加了object,因为它变成了一个对象,并且工作正常。唯一的问题是我无法访问类中的字符串(用户名和密码)。我不能像这样写:otherItem.username或otherItem.password。