Saturday, 15 June 2013

c# - Two clone variables return the same index on a list -



c# - Two clone variables return the same index on a list -

i have list has number of objects class x.

i add together 1 object via clone function, gets own index, if add together 1 more object using clone, object receives same index first clone.

here 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)); } homecoming indexlist ; }

for example: if have 10 objects 1 of them made twice clone, have 12 objects , index of both clone same (they not sit down on same index, function indexof returns same one)

what can do?

edit:

public x clone() { x clone = new x(int32.parse(this.name.split(new char[1] { ' ' })[1]) + 1); clone.copy(this); homecoming clone; }

quoted msdn (emphasis own):

searches specified object , returns zero-based index of first occurrence within range of elements in list extends specified index lastly element.

they both matching first occurrence basically. boils downwards equality on items have in list<>, uses default equality comparer:

this method determines equality using default equality comparer equalitycomparer.default t, type of values in list.

http://msdn.microsoft.com/en-us/library/e4w08k17.aspx

you utilize override takes starting index preclude prior indices search:

http://msdn.microsoft.com/en-us/library/s8t42k5w.aspx

or, if want hold unique items based on hash , equality, utilize hashset<t> instead.

i thought offering code sample, when @ code provide makes less , less sense. current sample loop items in index order , add together index list, duplicate items it'll same index. taking step back, what trying achieve? sense there's improve option.

c# list clone

No comments:

Post a Comment