简体   繁体   English

根据特定条件从C#中的列表中删除列表

[英]Remove list from a list in C# based on specific condition

I want to remove objects of one list that are present on other list according to condition here are my two lists 我想根据条件删除一个列表中存在于另一列表中的对象,这是我的两个列表

List Structure 清单结构

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

list2 = {userId , ParentId , GuideId , Status }

data for list one 清单一的数据

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} 

data for list 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} 

these data come from db it may be thousand 这些数据来自数据库,可能是一千

but I need where GuideId matches it would remove the data from list 但我需要在GuideId匹配的地方从列表中删除数据

what I applied is not working 我申请的内容不起作用

Here is the code 这是代码

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

Here is my Code 这是我的代码

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

That doesn't work because Except doesn't know how you want to compare the objects. 那是行不通的,因为Except不知道您要如何比较对象。 So it just compares references. 因此,它只是比较参考。 You have to override Equals + GetHashCode or you have to provide a custom IEqualityComparer<T> . 您必须重写Equals + GetHashCode或者必须提供自定义IEqualityComparer<T>

But you could also use List.RemoveAll instead: 但是您也可以改用List.RemoveAll

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

您可以尝试根据GuideId删除

List2.Where(x => !List1.Select(y => y.GuideId).Contains(x.GuideId))

另一种方法是在linq中使用foreach,此方法仅比较ID,无需覆盖或引用相等:

list2.ForEach(x => list.RemoveAll(y => y.GuidId == x.GuidId));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM