集合里的元素莫名奇妙的丢失了!!!!请教,,,,,C#入门经典里的题
c#入门经典11章第三题这是我的算法:
public Person[] GetOldest1()
{
People tmPeople = new People();
Person MaxPerson = new Person();
MaxPerson.Age = 0; MaxPerson.Name = "";
foreach (DictionaryEntry everyone in Dictionary)
{
if (everyone.Value as Person> MaxPerson)
MaxPerson = everyone.Value as Person;
}
tmPeople.Add(MaxPerson);在 tempPeople加入最大的那一项
this.Remove(MaxPerson.Name);在本集合中把那项删去
foreach (DictionaryEntry everyone in Dictionary)
{
if (everyone.Value as Person>= MaxPerson)
tmPeople.Add(everyone.Value as Person);
}
Person[] newPeople = new Person[tmPeople.Count];
int copyIndex = 0;
foreach(DictionaryEntry everyone in tmPeople)
{
newPeople[copyIndex] = everyone.Value as Person;
copyIndex++;
}
return newPeople;
}
我的方法所产生的问题是:返回的Person数组会总会缺一项,就是代码里MaxPerson所代表的那一项...请教大家是什么问题...
下面是答案里给出的算法,除了效率之外,我觉得似乎也没什么不一样的...
public Person[] GetOldest()
{
Person oldestPerson = null;
People oldestPeople = new People();
Person currentPerson;
foreach (DictionaryEntry p in Dictionary)
{
currentPerson = p.Value as Person;
if (oldestPerson == null)
{
oldestPerson = currentPerson;
oldestPeople.Add(oldestPerson);
}
else
{
if (currentPerson > oldestPerson)
{
oldestPeople.Clear();
oldestPeople.Add(currentPerson);
oldestPerson = currentPerson;
}
else
{
if (currentPerson >= oldestPerson)
{
oldestPeople.Add(currentPerson);
}
}
}
}
Person[] oldestPeopleArray = new Person[oldestPeople.Count];
int copyIndex = 0;
foreach (DictionaryEntry p in oldestPeople)
{
oldestPeopleArray[copyIndex] = p.Value as Person;
copyIndex++;
}
return oldestPeopleArray;
} --------------------编程问答-------------------- 集合长度 --------------------编程问答--------------------
楼上的能不能说的具体点,谢谢. --------------------编程问答-------------------- this.Remove(MaxPerson.Name);
这句是删除什么?
this表示啥?
--------------------编程问答-------------------- 试试:
Dictionary.Remove(MaxPerson.Name);
补充:.NET技术 , C#