使用自定义类时,在GroupBy中选择第一项

时间:2013-05-07 00:35:50

标签: linq

我有一个非常基本的sql视图,它连接3个表:用户,图片和标签。

如何以不会多次列出相同图片的方式创建下面的查询?换句话说,我想分组照片(我认为)并返回获得每个的第一个内容。

我认为这与帖子Linq Query Group By and Selecting First Items非常相似,但我无法弄清楚如何在查询实例化MyImageClass的情况下应用它。

        validPicSummaries = (from x in db.PicsTagsUsers
         where x.enabled == 1
           select new MyImageClass { 
               PicName = x.picname, 
               Username= x.Username, 
               Tag = x.tag }).Take(50);

1 个答案:

答案 0 :(得分:3)

要排除重复项,您可以使用Distinct LINQ方法:

validPicSummaries =
   (from x in db.PicsTagsUsers
    where x.tag == searchterm && x.enabled == 1
    select new MyImageClass
    { 
       PicName = x.picname, 
       Username= x.Username, 
       Tag = x.tag
    })
    .Distinct()
    .Take(50);

您需要确保对象具有可比性,以便将具有相同MyImageClassPicNameUsername的两个Tag对象视为相等(或但是你想考虑其中两个是平等的。

如果你想为这种情况设置自定义比较器,你可以编写一个实现IEqualityComparer<T>的小类。例如:

  private class MyImageClassComparer : IEqualityComparer<MyImageClass>
  {
     public bool Equals(MyImageClass pMyImage1, MyImageClass pMyImage2)
     {
        // some test of the two objects to determine 
        // whether they should be considered equal

        return pMyImage1.PicName == pMyImage2.PicName
           && pMyImage1.Username == pMyImage2.Username
           && pMyImage1.Tag == pMyImage2.Tag;
     }

     public int GetHashCode(MyImageClass pMyImageClass)
     {
        // the GetHashCode function seems to be what is used by LINQ
        // to determine equality. from examples, it seems the way
        // to combine hashcodes is to XOR them:

        return pMyImageClass.PicName.GetHashCode()
           ^ pMyImageClass.UserName.GetHashCode()
           ^ pMyImageClass.Tag.GetHashCode();
     }
  }

然后当你打电话给不同的时候:

    ...
    .Distinct(new MyImageClassComparer())
    .Take(50);