LINQ从IList< T>中删除某些元素.基于IList< int> [英] LINQ to remove certain elements from a IList<T> based on a IList<int>

查看:59
本文介绍了LINQ从IList< T>中删除某些元素.基于IList< int>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用LINQ从基于另一个IList的IList中删除某些元素.我需要从列表1中删除ID中存在ID的记录.下面是代码示例,

How to use LINQ to remove certain elements from a IList based on another IList. I need to remove records from list1 where ID is present in list2. Below is the code sample,

class DTO
{

    Prop int ID,
    Prop string Name
}

IList<DTO> list1;

IList<int> list2;



foreach(var i in list2)
{
    var matchingRecord = list1.Where(x.ID == i).First();
    list1.Remove(matchingRecord);
}

我就是这样做的,有没有更好的方法来做同样的事情.

This is how I am doing it, is there a better way to do the same.

推荐答案

您可以为 IList< T> 编写一个"RemoveAll()"扩展方法,其工作方式与 List.RemoveAll().(这通常足以保存在通用类库中.)

You could write a "RemoveAll()" extension method for IList<T> which works exactly like List.RemoveAll(). (This is generally useful enough to keep in a common class library.)

例如(为了清楚起见,删除了错误检查;您需要检查参数是否不为空):

For example (error checking removed for clarity; you'd need to check the parameters aren't null):

public static class IListExt
{
    public static int RemoveAll<T>(this IList<T> list, Predicate<T> match)
    {
        int count = 0;

        for (int i = list.Count - 1; i >= 0; i--)
        {
            if (match(list[i]))
            {
                ++count;
                list.RemoveAt(i);
            }
        }

        return count;
    }        

然后根据需要从list1中删除项目确实很简单:

Then to remove the items from list1 as required would indeed become as simple as:

list1.RemoveAll(item => list2.Contains(item.ID));

这篇关于LINQ从IList&lt; T&gt;中删除某些元素.基于IList&lt; int&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆