C#Linq Group by Distinct不工作

时间:2015-11-18 15:11:20

标签: c# linq

我已经在这里回顾了很多关于如何通过在列表对象上使用LINQ语句进行分组的文章,但是即使所有变量具有完全相同的值,以下代码也无法对任何内容进行分组。有人可以告诉我为什么这可能不起作用?它与LINQ延迟执行有关吗?我已经尝试了一个示例,其中包含了第二个选择语句但没有帮助。我传入一个list<MyClass>对象,该对象有两个相同的项目而另一个没有,所以当这个语句执行时我应该只收到两个项目。

代码中的实际值:

   Type = 1, Capacity = 50, Goal = "Teach algebra", 
   Attachments = "", Hours = 1, TypeDesignation = 3, 
   TypeControl = 1, Supplies = 0 

   TypeControl and Supplies are both objects themselves. Supplies is empty.
   TypeControl contains Id = 23, Text = "Math", Active = 1

        var test = newclass.GroupBy(n => new 
        {
            n.Type,
            n.Capacity,
            n.Goal,
            n.Attachments,
            n.Hours,
            n.TypeDesignation,
            n.TypeControl,
            n.Supplies

        }).Distinct().Select(n => new MyClass()
        {
            Type = n.Key.Type,
            Capacity = n.Key.Capacity,
            Goal = n.Key.Goal ,
            Attachments = n.Key.Attachments,
            Hours = n.Key.Hours ,
            TypeDesignation = n.Key.TypeDesignation,
            TypeControl = n.Key.TypeControl,
            Supplies = n.Key.Supplies
        });

1 个答案:

答案 0 :(得分:0)

我的问题的答案是内部的所有对象实际上都不相等,因为我有一个子对象,在一个对象的组中被读取为null而另一个对象被读取为0所以他们永远不能组合在一起但是当我用intellisense看他们时他们总是说空。我通过循环遍历列表并使用比较器方法深入查看子对象并找出差异来解决问题。

        VerifyDuplicates duplicates = new VerifyDuplicates();

        List<MyClass> newClass = new List<MyClass>(); 

        classes = classes.OrderBy(s => s.Type).ToList();
        List<int> idsToDelete = new List<int>();
        for (int i = 0; i < classes.Count; i++)
        {
            if (i + 1 < classes.Count)
            {
                var x = duplicates.Compare(classes[i], classes[i + 1]);
                if (x == 1)
                    idsToDelete.Add(classes[i+1].Id);
            }
        }
        newClass = classes.Where(n => !idsToDelete.Contains(n.Id)).Select(n => n).ToList();

    public class VerifyDuplicates : Comparer<MyClass>
    {
        public override int Compare(MyClass x, MyClass y)
        {
            int p = 0;

            if(x != null && y != null)
            { 
                if(x.Type.Equals(y.Type)) { p += 1; }
                if(x.Attachments.Equals(y.Attachments)) { p += 1; }
                if(x.Capacity.Equals(y.Capacity)) { p += 1; }
                if(x.Goal.Equals(y.Goal)) { p += 1; }
                if(x.Hours.Equals(y.Hours)) { p += 1; }
                if(x.TypeDesignation.Equals(y.TypeDesignation)) { p += 1; }
                if(x.TypeControl != null && y.TypeControl != null)
                    if(x.TypeControl[0].Equals(y.TypeControl[0])) { p += 1; }
                if(x.Supplies != null && y.Supplies!= null)
                    if (x.Supplies.Equals(y.Supplies)) { p += 1; }

                return p;
            }
      }
  }