Reputation: 421
Is it possible to get an item's position in a list to do something like the following?…
public class ListItem
{
public override string ToString()
{ return PositionInList.ToString(); }
}
public List < ListItem > myList = new List < ListItem >();
Upvotes: 1
Views: 196
Reputation: 1376
using the .IndexOf()
method of the List class will allow you to do that.
var lst = new List<string>();
lst.Add("foo");
lst.Add("bar");
// Output the index, ie: 1
Console.WriteLine(lst.IndexOf("bar"));
Upvotes: -1
Reputation: 61369
I'm not saying you should do this, because a class knowing about its container is just odd, but you could do:
List<ListItem> parentList;
public ListItem(List<ListItem> parentList)
{
this.parentList = parentList;
}
public override string ToString()
{ return parentList.IndexOf(this).ToString(); }
Of course, during construction you need to pass the parent collection in.
Upvotes: 1
Reputation: 101701
There should be a connection between ListItem
and List
. For example you can add a property to store the list that has the ListItem
:
public List<ListItem> List { get; set; }
public List <ListItem> myList = new List <ListItem>();
myList.Add(new ListItem { List = myList });
Then you can use IndexOf
method:
public override string ToString()
{
return List.IndexOf(this).ToString();
}
Upvotes: 1