查找返回列表结果的索引C#

时间:2018-03-16 16:26:38

标签: c# string list indexing indexof

如何在列表中找到条目的索引。我的代码如下。

listFromlistTo包含字符串条目。

我收到错误:

  

严重级代码描述项目文件行抑制状态   错误CS1503参数1:无法转换为' System.Collections.Generic.List'到'字符串'

List<string> listFrom = new List<string>(); //Contains a list of strings
List<string> listTo = new List<string>(); //Contains a list of strings

List<string> lineStart = listFrom.Except(listTo).ToList(); //Will always return a single value
List<string> lineEnd = listTo.Except(listFrom).ToList(); //Will always return a single value

int startLineIndex = listFrom.IndexOf(lineStart);            //Error on this line
Console.WriteLine("Index of Start: " + startLineIndex);

2 个答案:

答案 0 :(得分:1)

如错误所述,它无法从'System.Collections.Generic.List'转换为'string'。但是我从来不知道函数SingleOrDefult()存在。

All credit to @maccettura even though he didn't know what I was trying to do! xD

以下代码更改答案:

List<string> listFrom = new List<string>(); //Contains a list of strings
List<string> listTo = new List<string>(); //Contains a list of strings

string lineStart = listFrom.Except(listTo).SingleOrDefault();
string lineEnd = listFrom.Except(listTo).SingleOrDefault();

int startLineIndex = listFrom.IndexOf(lineStart);            //Error on this line
Console.WriteLine("Index of Start: " + startLineIndex);

答案 1 :(得分:0)

这是因为当你致电listFrom.IndexOf(lineStart);时,它会期待一个字符串。代码中的lineStart被定义为字符串列表,因此您需要调用列表中的特定值,或将lineStart更改为字符串。