Linq Group以每个空值作为一个组 [英] Linq GroupBy with each null value as a group

查看:111
本文介绍了Linq Group以每个空值作为一个组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有空的int属性GroupId的对象。

使用这个对象的List,我想在这个GroupId上做一个GroupBy, 。但是,如果我这样做,所有的空值将形成一个组。



示例:

对象1: GroupId:NULL



对象2:GroupId:NULL

对象3:GroupId:1



对象4:GroupId:1



对象5:GroupId:2



<对象6:GroupId:2

  MyList.GroupBy(f => f.GroupId,key => new { Object = key}); 

我会得到3组。



我怎样才能得到4组?为每个NULL值... ...

解决方案

这可能是最短的解决方案:

  var grouped = MyList.GroupBy(f => f.GroupId!= null?(object)f.GroupId:new object(),key => new {Object = key}); 

请注意,组的键将是 object 类型。对于 null 元素,我创建了一个新的空对象。对象的相等比较器会使它们都不同。对于非空数字,我只是将它们放在一个对象中。盒装整数保持相等运算符。所以:

  new object()。Equals(new object())== false // always 
code>

 ((对象)1).Equals((object)1)== true //总是

和 ((object)1).Equals((object)2)== false // always

更正确的解决方案是实现 IEqualityComparer< int?> p>

  public class MyComparer:IEqualityComparer< int?> {
public bool Equals(int?x,int?y){
if(x == null || y == null){
return false;
}

return x.Value == y.Value;
}

public int GetHashCode(int?obj){
return obj.GetHashCode(); //即使obj为空也是有效的:-)
}
}

并使用它:

  var grouped2 = MyList.GroupBy(f => f.GroupId,key => new {Object = key},new MyComparer()); 


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 values will form a group.

Example :

Object 1 : GroupId : NULL

Object 2 : GroupId : NULL

Object 3 : GroupId : 1

Object 4 : GroupId : 1

Object 5 : GroupId : 2

Object 6 : GroupId : 2

MyList.GroupBy(f => f.GroupId, key => new {Object = key});

I will get 3 groups.

How can I get 4 groups instead ? A group for each NULL value...

解决方案

This is probably the shortest solution:

var grouped = MyList.GroupBy(f => f.GroupId != null ? (object)f.GroupId : new object(), key => new { Object = key });

Note that the "key" of the groups will be of object type. For null elements I create a new "empty" object. The equality comparer of objects will make so that they are all different. For not-null numbers I simply box them in an object. Boxed integers maintain the equality operator. So:

new object().Equals(new object()) == false // always

and

((object)1).Equals((object)1) == true // always

and

((object)1).Equals((object)2) == false // always

a more correct solution would be implementing an IEqualityComparer<int?>

public class MyComparer : IEqualityComparer<int?> {
    public bool Equals(int? x, int? y) {
        if (x == null || y == null) {
            return false;
        }

        return x.Value == y.Value;
    }

    public int GetHashCode(int? obj) {
        return obj.GetHashCode(); // Works even if obj is null :-)
    }
}

and using it:

var grouped2 = MyList.GroupBy(f => f.GroupId, key => new { Object = key }, new MyComparer());

这篇关于Linq Group以每个空值作为一个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆