使用LINQ不等于

编程入门 行业动态 更新时间:2024-10-23 15:20:45
本文介绍了使用LINQ不等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有2列表收藏在我的C#app..A和B

I've 2 list collections in my C# app..A and B.

这两个集合有具有标识和名称attributes.Typically,A有超过B项。客户对象

Both the collections have customer object which has Id and Name attributes.Typically, A has more items than B.

使用LINQ,我想只返回客户的ID是A,但没有B中。

Using Linq,I want to return only those customers whose Id is in A but not in B.

我如何做到这一点?

推荐答案

有采取多种方式。最简洁的方法是使用除了扩展方法,如果你已经重写等于和 GetHash $ C $ç。如果你还没有,还有其他的选择。

There are multiple approaches to take. The cleanest approach is to use the Except extension method if you have overriden Equals and GetHashCode. If you have not, there are other options.

// have you overriden Equals/GetHashCode? IEnumerable<Customer> resultsA = listA.Except(listB); // no override of Equals/GetHashCode? Can you provide an IEqualityComparer<Customer>? IEnumerable<Customer> resultsB = listA.Except(listB, new CustomerComparer()); // Comparer shown below // no override of Equals/GetHashCode + no IEqualityComparer<Customer> implementation? IEnumerable<Customer> resultsC = listA.Where(a => !listB.Any(b => b.Id == a.Id)); // are the lists particularly large? perhaps try a hashset approach HashSet<int> customerIds = new HashSet<int>(listB.Select(b => b.Id).Distinct()); IEnumerable<Customer> resultsD = listA.Where(a => !customerIds.Contains(a.Id));

...

class CustomerComparer : IEqualityComparer<Customer> { public bool Equals(Customer x, Customer y) { return x.Id.Equals(y.Id); } public int GetHashCode(Customer obj) { return obj.Id.GetHashCode(); } }

更多推荐

使用LINQ不等于

本文发布于:2023-11-15 21:38:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不等于   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!