如何在列表中显示对象的位置

时间:2013-02-05 14:10:12

标签: c# list collections

我有一个完整的对象列表,我想显示每个对象“坐位”的位置:
喜欢:
 对象A-名称0
 对象B-名-1
 objectc名-2
 objectc名-3
 objectc-name-4 ---等等......

这是最好的方法吗? 谢谢:))

public List <Custome> custome = new List <Custome>();

   public override void Display(Custome c)
    {
     /////
    }

2 个答案:

答案 0 :(得分:3)

public override int Display(Custome c)
{
    return custome.IndexOf(c);
}

答案 1 :(得分:1)

不确定我是否完全理解,但您可以使用带有索引表达式的Select重载:

var newList = custome.Select((c, i)=>new {Custome=c, Index = i});
foreach(var item in newList)
{
    Console.WriteLine("{0} - {1}",item.Custome.Name, item.Index);
}

或者,如果您只是想找到一个项目的位置,请使用

public override void Display(Custome c)
{
    int index = custome.IndexOf(c);
    Console.WriteLine("{0} - {1}",c.Name, index);
}