C# 控制台编号列表不确定如何调用列表中项的索引



我无法获得适用于我的代码的编号列表,我希望它看起来像这样: 1 - 鱼 2 - 豆类 3 - 汽车

inventoryList.Add"Fish";
inventoryList.Add"Beans";
inventoryList.Add"Car";
foreach (string item in inventoryList)
{
Console.WriteLine((item.IndexOf(item) + 1) + " - " + item);
}
Console.ReadLine();

您应该在字符串列表中调用IndexOf方法。

Console.WriteLine((inventoryList.IndexOf(item) + 1) + " - " + item);

由于您只想为列表中的项目打印一个计数器,因此您可以避免对列表进行IndexOf调用,而只需将其替换为局部计数器变量即可。IndexOf方法必须检查字符串项中的每个字符以及列表中每个项中的每个字符,因此可以执行n*m复杂操作

var counter = 0;
foreach (string item in inventoryList)
{
Console.WriteLine(++counter + " - " + item);
}

我不建议使用IndexOf,因为它运行的时间O(n),因此在列表迭代中,它将是O(n*n)的顺序,这很糟糕。

在循环访问列表时,您需要跟踪项目编号。foreach不像for,因为没有隐式索引。

您可以使用 Linq 的.Select( item, index )重载,也可以自己跟踪它:

foreach( var pair in inventoryList.Select( (e,i) => new { Index = i, Value = e } )
{
Console.WriteLine( "{0} - {1}", pair.Index + 1, pair.Value );
}

或:

Int32 index = 0;
foreach( String item in inventoryList )
{
Console.WriteLine( "{0} - {1}", index + 1, item );
index++;
}

或:

for( Int32 i = 0; i < inventoryList.Count; i++ )
{
Console.WriteLine( "{0} - {1}", i + 1, inventoryList[i] );
}

使用 Linq 试试这个:

inventoryList.Select((item, index) => new { Index = index, Name = item })
.ToList()
.ForEach(it =>
{
Console.WriteLine("{0} - {1}", it.Index + 1, it.Name);
});

在列表中使用 indexOf 不是一个好的选择,请尝试这种方式。

IndexOf 方法执行线性搜索;因此,此方法是一个 O(n( 操作,其中 n 是元素数。

inventoryList.Add"Fish"; inventoryList.Add"Beans"; inventoryList.Add"Car"; 
var index = 1;
foreach (string item in inventoryList) { 
Console.WriteLine(index + " - " + item); 
index++;
}
Console.ReadLine();

最新更新