在项目中打印项目的索引

问题描述 投票:0回答:1

我想让列表中的一个项目的索引在打印时出现在该项目中,所以类似于

List<string> listy = new List<string>();
listy.Add("Index of this item is: " + index);

我希望索引是一个可以在方法中作为参数传递的对象。

c# list indexof
1个回答
0
投票
List<string> listy = new List<string>();
listy.Add("Index of this item is: " + list.Count);

在这种特殊情况下,应该是可行的,因为Add在列表的最后添加了一个项目,新的最后一个项目的索引将等于旧的计数。


0
投票

将 "索引 "与你要添加到列表中的项的值相一致,就可以在列表中添加项。List 在添加项目的时候,并不是一个好主意。的实际 index 的条目 List 可以 一生一世 List 由于业务,如 RemoveAt, Insert, SortReverse 仅举几例。仅仅因为这个原因,人们就应该评估 index 在需要的时候。

OP的问题说明是 "打印索引"。我将按字面意思理解。所以让我们打印(!)该项目的索引.只需使用:

myList.ForEach(x => Console.WriteLine($"{x}:{lx.IndexOf(x)}"));

让我们看看这在代码中是如何工作的。

    private static void PrintWithIndexBetterIdea()
    {
        var lx = new List<string>();
        lx.Add("A ");
        lx.Add("B ");
        lx.Add("C ");
        lx.Insert(2, "D ");
        lx.ForEach(x => Console.WriteLine($"Item {x} real index: {lx.IndexOf(x)}"));
    }

这就是为什么把索引和你输入的项目连在一起不是一个好主意。有一个方法属于 List 叫做 Insert. 你可以在列表中插入一个新的项目,这使得 "硬编码 "的变化变得无用。来演示一下。

    private static void PrintWithIndexBadIdea()
    {
        var lx = new List<string>();
        lx.Add("A " + lx.Count);
        lx.Add("B " + lx.Count);
        lx.Add("C " + lx.Count);
        lx.Insert(2, "D 2");
        lx.ForEach(x => Console.WriteLine(x));

        lx.ForEach(x => Console.WriteLine($"Item{x} real index: {lx.IndexOf(x)}"));
    }

结果:

From PrintWithIndexBadIdea:
A 0
B 1
D 2
C 2
ItemA 0 real index: 0
ItemB 1 real index: 1
ItemD 2 real index: 2
ItemC 2 real index: 3

From PrintWithIndexBetterIdea 
Item A  real index: 0
Item B  real index: 1
Item D  real index: 2
Item C  real index: 3
© www.soinside.com 2019 - 2024. All rights reserved.