根据特定条件从C#中的列表中删除列表 [英] Remove list from a list in C# based on specific condition

查看:32
本文介绍了根据特定条件从C#中的列表中删除列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据条件删除一个列表中存在于另一个列表中的对象,这是我的两个列表

I want to remove objects of one list that are present on other list according to condition here are my two lists

列表结构

list1 = {GuideId ,Text , Desc , SecId , NextBtnText , ParentId}

list2 = {userId , ParentId , GuideId , Status }

列表一的数据

list1[0]{GuideId = 1 , Text=abc , Desc=any , SecId =2 , ParentId = 2}

list1[1]{GuideId = 2 , Text=abc , Desc=any , SecId =2 , ParentId = 2}

list1[2]{GuideId = 3 , Text=abc , Desc=any , SecId =2 , ParentId = 2}

list1[3]{GuideId = 4 , Text=abc , Desc=any , SecId =2 , ParentId = 2}

list1[4]{GuideId = 5 , Text=abc , Desc=any , SecId =2 , ParentId = 2} 

列表2的数据

list2[0]{GuideId = 1 , Text=abc , Desc=any , SecId =2 , ParentId = 2}

list2[1]{GuideId = 2 , Text=abc , Desc=any , SecId =2 , ParentId = 2}

list2[2]{GuideId = 3 , Text=abc , Desc=any , SecId =2 , ParentId = 2} 

这些数据来自db,可能是一千个

these data come from db it may be thousand

但是我需要在GuideId匹配的地方将其从列表中删除

but I need where GuideId matches it would remove the data from list

我申请的内容无效

这是代码

List1 = List1.Except(List2).ToList();

这是我的代码

  userGuideList = query.ToList<GuidedPopupsViewModel>();
     popUpGuideListVm = query2.ToList<GuidedPopupsViewModel>();
    popUpGuideListVm = popUpGuideListVm.Except(userGuideList).ToList();

推荐答案

这不起作用,因为 Except 不知道您要如何比较对象.因此,它只是比较参考.您必须覆盖 Equals + GetHashCode 或者您必须提供自定义 IEqualityComparer.

That doesn't work because Except doesn't know how you want to compare the objects. So it just compares references. You have to override Equals + GetHashCode or you have to provide a custom IEqualityComparer<T>.

但是您也可以使用 List.RemoveAll 代替:

But you could also use List.RemoveAll instead:

List1.RemoveAll(x=> List2.Any(x2 => x2.GuideId == x.GuideId));

这篇关于根据特定条件从C#中的列表中删除列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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