如何筛选和排除列表项 [英] How to filter and exclude from list items

查看:107
本文介绍了如何筛选和排除列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表{id,name}

和另一个对象列表{id,name}



我想要用列表2的项目过滤列表1.



所以我的第一个列表有数据

1 John

2 Josh

3 Ann

4笔



我的secont列表有数据

3 Ann

4笔



我想过滤1个清单只是为了拥有2条记录

1 John

2 Josh



我的尝试:



I have one list of object1 {id, name}
and another list of object2 {id, name}

I want to filter list 1 with items of list 2.

so my first list have data
1 John
2 Josh
3 Ann
4 Pen

my secont list have data
3 Ann
4 Pen

I want to filter 1 list just to have 2 records
1 John
2 Josh

What I have tried:

List<object1> items1
List<Object2> items2
List<object1> result = items1.Where(item => items2.Any(x => x.id.Equals(item.id))).ToList();





不起作用



that doesn't work

推荐答案

您正在选择items1中与items2匹配id的项目,这与您想要的相反。你想要没有匹配的地方所以使用!对于不代替



You're selecting the items from items1 that have a matching id in items2 which is the opposite of what you want. You want where there is no match so use "!" for "not" instead

List<object1> result = items1.Where(item => !items2.Any(x => x.id.Equals(item.id))).ToList();


作为 F-ES Sitecore [ ^ ]已经写过,你需要使用NOT - 运算符! 。

你也引用不同的类(object1和object2):



As F-ES Sitecore[^] already wrote, you need to use the NOT - operator "!".
Also you reference to different classes (object1 and object2):

List<object1> items1
List<Object2> items2





这里有一个通用类string的工作示例,以了解它是如何工作的:





Here a working example with generic class "string" to understand how it works:

List<string> items1 = new List<string>(new string[] { "John", "Josh", "Ann", "Pen" });
List<string> items2 = new List<string>(new string[] { "Ann", "Pen" });
List<string> result = items1.Where(item => !items2.Any(x => x.Equals(item))).ToList();


除了解决方案#1和#2之外,我建议使用众所周知的 Enumerable.Except Method(System.Linq)| Microsoft Docs [ ^ ]以获取两个列表之间的差异。

如果您想要获得两个列表的共同部分,请使用: Enumerable.Intersect Method(System.Linq)| Microsoft Docs [ ^ ]
In addition to solution #1 and #2, i'd suggest to use well known Enumerable.Except Method (System.Linq) | Microsoft Docs[^] to get the difference between two lists.
In case you want to get common part of both list, use: Enumerable.Intersect Method (System.Linq) | Microsoft Docs[^]


这篇关于如何筛选和排除列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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