1

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

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

我认为这与帖子Linq Query Group By 和 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);
4

1 回答 1

3

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

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);

您需要确保对象是可比较的,以便MyImageClass具有相同PicNameUsername和的两个对象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);
于 2013-05-07T00:41:20.797 回答