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
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
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. So it just compares references. You have to override Equals
+ GetHashCode
or you have to provide a custom IEqualityComparer<T>
.
But you could also use List.RemoveAll
instead:
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.