.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;
        }
    

posted on 2024-09-06 08:26  norsd  阅读(2)  评论(0编辑  收藏  举报  来源

导航