.net Linq注意事项

Reference:
https://www.cnblogs.com/lyj/archive/2008/01/27/1054995.html

  1. 关于Except:
    不能说是取两个集合的不同项。很多中文Blog却想当然的这么写了。
    Except的返回值在文档中是这么描述的:
    https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=net-5.0

    Returns
    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不一样的元素…坑爹

  2. 关于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;
        }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值