首页 > 解决方案 > LINQ 除了不检索重复项

问题描述

我在 c# 中有两个列表,我想检索 listaA 上所有不在 listaB 中的元素,所以我决定使用 except 方法,如下面的代码:

List<string> listaA = new List<string>() { "a", "b", "b", "c", "d", "e", "e" };
List<string> listaB = new List<string>() { "e" };

var inter = listaA.Intersect(listaB);
var excep = listaA.Except(listaB).Count();

除了输出 - > 4

但是我的预期输出应该是 5,因为我们有两个“b”,所以如果在 ListaA 中我们排除了 listaA 中存在的所有元素,为什么输出是 4 而不是 5,我怎样才能让它按我的预期工作?

标签: c#linq

解决方案


你可以做Where,然后得到Count的输出:

var result = listaA.Where(x =>!listaB.Contains(x));
var newcount=result.Count();

推荐阅读