Reputation: 4417
I have a list which has a number of objects from class X.
I add one object via clone
function, it gets its own index, but if I add one more object using the clone, the object receives the same index as the first clone.
Here some code:
public void AddCopyObj(List<x> MyList, int Idx)
{
x AddCloneObj=MyList[Idx].Clone();
MyList.Insert(Idx+1,AddCloneObj)
}
public List<int> GetAllIndexs(List<x> MyList)
{
List<int> IndexList = new List<int>();
foreach(x myXvar in MyList)
{
IndexList.add(MyList.IndexOf(myXvar));
}
return IndexList ;
}
For example: If I have 10 objects to one of them I made twice clone, I will have 12 objects and index of both the clone be the same (they do not sit on the same index, the function IndexOf returns the same one)
What can I do?
EDIT:
public x Clone()
{
x clone = new x(Int32.Parse(this.Name.Split(new char[1] { ' ' })[1]) + 1);
clone.Copy(this);
return clone;
}
Upvotes: 0
Views: 110
Reputation: 4417
The problem was I did not do twice clone,
I took the same object and put it twice in the list,
after I had done twice clone issue is resolved.
(Sorry, it was not on a question, you could not tell.)
Upvotes: 0
Reputation: 64517
Quoted from MSDN (emphasis my own):
Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List that extends from the specified index to the last element.
They are both matching the first occurrence basically. This boils down to equality on the items you have in List<>
, it uses the default equality comparer:
This method determines equality using the default equality comparer EqualityComparer.Default for T, the type of values in the list.
http://msdn.microsoft.com/en-us/library/e4w08k17.aspx
You could use the override that takes a starting index to preclude prior indices from the search:
http://msdn.microsoft.com/en-us/library/s8t42k5w.aspx
Or, if you want to hold unique items based on hash and equality, use HashSet<T>
instead.
I thought about offering a code sample, however when I look at the code you provide it makes less and less sense. You current sample will loop the items in index order and add the index to another list, only for duplicate items it'll be the same index. Taking a step back, what are you trying to achieve? I get the sense there's a better option.
Upvotes: 2