List.Remove处理的巧妙思维
//【方法一:先遍历出来,只记录索引号,然后统一删除】
List<int> aIndex = new List<int>();
for (int i = 0; i < this.AttachmentList.Count; i++)
{
if (this.AttachmentList[i] != null && this.AttachmentList[i].AttachmentName == fileName)
{
aIndex.Add(i);
}
}
for (int i = 0; i < aIndex.Count; i++)
{
//?删除的时候还是有点问题,就是删完一个后,下面的索引都上移了。处理方式如下:
this.AttachmentList.RemoveAt(i == 0 ? aIndex[i] : (aIndex[i] - i));
}
//【方法二:一边遍历,一边删除】
for (int i = 0; i < this.AttachmentList.Count; i++)
{
if (i == this.AttachmentList.Count)
return;
if (this.AttachmentList[i] != null && this.AttachmentList[i].AttachmentName == fileName)
{
this.AttachmentList.RemoveAt(i);
//?删除的时候还是有点问题,就是删完一个后,下面的索引都上移了,要把循环退一步:
i--;
}
}
//【方法三:自己做了以上两种之后,问同事是否有更好的方法,同事给出巧妙的办法,倒着遍历,什么别扭都没有了!!!!!!】
for (int i = this.AttachmentList.Count - 1; i >= 0; i--)
{
if (this.AttachmentList[i] != null && this.AttachmentList[i].AttachmentName == fileName)
{
this.AttachmentList.RemoveAt(i);
}
}
总结:
一开始就知道第三种方法的,有,
一开始就使用3.5,不用自己处理这种事情的,也有;
一开始就写了第一种方法或第二中方法的,也有;
写完了,又问一问别人有没有更好的方法的,不多,这是程序员大多自傲的表现;
写完了,问别人了,别人不知道,或者知道不告诉你的,也有;
问了,得到第三种方法,但不高兴的,也有;
其实,很多巧妙的方法,是创造,是艺术,我们想不出,原本很正常。这不像考试,考试默认告诉你这个题有答案。
如果有一个题目就像上面的程序,给了你前两种方法,然后告诉你还有一种更巧妙的方法,你一定想得出来(这个不太一定哦)。
不一定有答案的题目,我们都最大限度的懒得去做。