0

我有一个列表,其中包含 X 类的许多对象。

我通过clone函数添加一个对象,它有自己的索引,但如果我使用克隆添加一个对象,该对象将接收与第一个克隆相同的索引。

这里有一些代码:

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 ;
}

例如:如果我有 10 个对象,其中一个我做了两次克隆,我将有 12 个对象,并且两个克隆的索引相同(它们不在同一个索引上,函数 IndexOf 返回相同的一个)

我能做些什么?

编辑:

public x Clone()
    {
        x clone = new x(Int32.Parse(this.Name.Split(new char[1] { ' ' })[1]) + 1);
        clone.Copy(this);
        return clone;
    }
4

2 回答 2

2

引用自 MSDN(强调我自己的):

搜索指定对象并返回List 中从指定索引延伸到最后一个元素的元素范围内第一次出现的从零开始的索引。

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.

于 2013-02-13T13:04:04.763 回答
0

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.)

于 2013-02-13T13:54:57.307 回答