代码改变世界

有列表List的操作所学习到的

2010-07-14 13:09  MichaelYin  阅读(263)  评论(0编辑  收藏  举报

前几日coding的时候,需要实现在泛型列表中找到其中的一个对象并将其移除的功能,刚开始想的很简单,先上代码

foreach (AttachmentBox objAttachmentBox in lsAttachments)
                {
                    if (objAttachmentBox.AttachmentId == int.Parse(e.CommandArgument.ToString()))
                        lsAttachments.Remove(objAttachmentBox);
                }

这是我刚开始写的代码。。

运行时候VS提示错误 “集合已修改;可能无法执行枚举操作。”跑到博客园里面找了一番,发现使用foreach就会存在这个问题,因为foreach在遍历的时候只取只读的数据,如果用for的话,就能够比避免这个问题。

好吧,那就换成for循环吧。

 

for (int i = 0; i <= lsAttachments.Count(); i++)
                {
                    if (lsAttachments[i].AttachmentId == int.Parse(e.CommandArgument.ToString()))
                        lsAttachments.RemoveAt(i);
                }

运行程序显示成功,不过不小心瞄到了List的RemoveAll的方法,饿。。是虾米意思呢?打开vs帮助查了一下,原来是使用委托找到相应的对象,并移除

MSDN里面的代码是这样写的。。。。

 private static bool EndsWithSaurus(String s)
    {
        if ((s.Length > 5) && 
            (s.Substring(s.Length - 6).ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

在单独的函数里面实现逻辑的话我的e.CommandArgument可不方便,感觉有点丑陋。。。等下等下,不是有匿名委托么?

这是第三个版本

 lsAttachments.RemoveAll(delegate(AttachmentBox attach) { return attach.AttachmentId == int.Parse(e.CommandArgument.ToString()); });

一行代码搞定,很优雅吧。。。不过呢。。。Lamda表达式会让它更有气质。。。

lsAttachments.RemoveAll( c =>  c.AttachmentId == int.Parse(e.CommandArgument.ToString()));