我有一个非常基本的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);
答案 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);
您需要确保对象具有可比性,以便将具有相同MyImageClass
,PicName
和Username
的两个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);