.net Linq注意事项
Reference:
https://www.cnblogs.com/lyj/archive/2008/01/27/1054995.html
-
关于Except:
不能说是取两个集合的不同项。很多中文Blog却想当然的这么写了。
Except的返回值在文档中是这么描述的:
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=net-5.0Returns IEnumerable<TSource> A sequence that contains the set difference of the elements of two sequences.
但是他还有一个Remark,在其中定义了"the set difference of the elements of two sequences"
其实挺怪的:Remarks The set difference of two sets is defined as the members of the first set that don't appear in the second set. This method returns those elements in first that don't appear in second. It doesn't return those elements in second that don't appear in first. Only unique elements are returned.
所以A.Except(B) 返回的是 A有B没有, 不包括B有A没有
也就是: A.Except(B) 不一定等于 B.Except(A)
我以前一直以为这个函数返回A,B不一样的元素…坑爹 -
关于Intersect:
Intersect 是取两个集合的交集,特别有用。交集的定义可以使用接口实现,否则就是集合元素自身是否一致来判断。
关于交集的定义,可以看StackOverFlow:https://stackoverflow.com/questions/853526/using-linq-to-remove-elements-from-a-listt
使用方法:
var list3= list1.Intersect(list2, new KeyEqualityComparer<ClassToCompare>(s => s.Id));
我自己稍微改了一下public class CommonEqualityComparer<T> : IEqualityComparer<T> { public CommonEqualityComparer(Func<T, object> arg_fnCompare) { this._fnCompare = arg_fnCompare; } public bool Equals(T x, T y) { return this._fnCompare(x).Equals(this._fnCompare(y)); } public int GetHashCode(T obj) { return this._fnCompare(obj).GetHashCode(); } private readonly Func<T, object> _fnCompare; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能