Linq-使用数组属性内的元素进行分组 [英] Linq - group by using the elements inside an array property

查看:53
本文介绍了Linq-使用数组属性内的元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多对象,每个对象都有一个数组,我想通过数组中的值对这些对象进行分组,因此从概念上讲,它们看起来如下:

I have a number of objects and each object has an array, I would like to group these objects by the values inside the array, so conceptually they look as follows:

var objects = new []{
  object1 = new object{
    elements = []{1,2,3}
  },
  object2 = new object{
    elements = []{1,2}
  },
  object3 = new object{
    elements = []{1,2}
  },
  object4 = new object{
    elements = null
  }
}

分组后:

group1: object1
group2: object2,object3
group3: object4

我尝试过的东西: 实际班级:

somethings that I have tried: actual classes:

    public class RuleCms
        {
            public IList<int> ParkingEntitlementTypeIds { get; set; }
        }


var rules = new List<RuleCms>()
        {
            new RuleCms()
            {
                ParkingEntitlementTypeIds = new []{1,2}
            },
            new RuleCms()
            {
                ParkingEntitlementTypeIds = new []{1,2}
            },
            new RuleCms()
            {
                ParkingEntitlementTypeIds = new []{1}
            },
            new RuleCms()
            {
                ParkingEntitlementTypeIds = null
            }
        };

var firstTry = rules.GroupBy(g => new { entitlementIds = g.ParkingEntitlementTypeIds, rules = g })
                    .Where(x => x.Key.entitlementIds !=null && x.Key.entitlementIds.Equals(x.Key.rules.ParkingEntitlementTypeIds));

var secondTry =
            rules.GroupBy(g => new { entitlementIds = g.ParkingEntitlementTypeIds ?? new List<int>(), rules = g })
                .GroupBy(x => !x.Key.entitlementIds.Except(x.Key.rules.ParkingEntitlementTypeIds ?? new List<int>()).Any());

推荐答案

您可以使用

You can use IEqualityComparer class. Here is the code:

class MyClass
{
    public string Name { get; set; }
    public int[] Array { get; set; }
}

class ArrayComparer : IEqualityComparer<int[]>
{
    public bool Equals(int[] x, int[] y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(int[] obj)
    {
        return string.Join(",", obj).GetHashCode();
    }
}

然后

var temp = new MyClass[]
{
    new MyClass { Name = "object1", Array = new int[] { 1, 2, 3 } },
    new MyClass { Name = "object2", Array = new int[] { 1, 2 } },
    new MyClass { Name = "object3", Array = new int[] { 1, 2 } },
    new MyClass { Name = "object4", Array =null }
};

var result = temp.GroupBy(i => i.Array, new ArrayComparer()).ToList();
//Now you have 3 groups

这篇关于Linq-使用数组属性内的元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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