Linq GroupBy with each null value as a group

后端 未结 2 875
旧巷少年郎
旧巷少年郎 2021-02-20 08:26

I have an object with a nullable int property \"GroupId\".

With a List of this object, I would like to do a GroupBy on this \"GroupId\". But if I do it, all the null val

2条回答
  •  情书的邮戳
    2021-02-20 08:54

    Generic Comparer that can be used without boxing.

    public class NullableComparer : IEqualityComparer
            where T : struct
    {
        public bool Equals(T? x, T? y)
        {
            if (x == null || y == null)
            {
                return false;
            }
    
            return x.Equals(y);
        }
    
        public int GetHashCode(T? obj)
        {
            return obj.GetHashCode();
        }
    }
    

    You would then use it like:

    // where GroupId as a nullable Guid 
    var grouped = MyList.GroupBy(f => f.GroupId, new NullableComparer());
    

提交回复
热议问题