使用LINQ to Entities从表中获取重复项

3

在我的数据库中,我有一个名为“hashcode”的列。此列存储图片的哈希码。我想运行一个使用linq to entities搜索重复哈希码的查询。

我卡在了“where子句”。我该如何比较哈希码?

var ans = this.pe.TPicture.Where(p => this.pe.TPicture.Count(x => x.Equals(p)) > 1);
1个回答

1

你可以使用count来学习Linq查询,参考http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

在你的情况下

entities.Where(p => entities.Count(x => x.Equals(p)) > 1);

以上查询的顺序是 O(n^2),但你可以用下面的代码简单地以 O(n log(n)) 的时间复杂度来实现。
            entities.Sort();

            List<x> repeatedItems = new List<x>();

            if (entities.Count > 1)
            {
                if (entities[0].Equals(entities[1]))
                {
                    repeatedItems.Add(entities[0]);
                }
            }

            for (int i=0;i<entities.Count;i++)
            { 
                if (i < entities.Count -1)
                {
                    if (entities[i].Equals(entities[i+1]))
                    {
                        repeatedItems.Add(entities[i+1]);
                    }
            }

你可以写成这样的代码:entities.Where(p => entities.Count(x => x.hashcode == p.hashcode) > 1); 这难吗? - Saeed Amiri
var ans = entities.Where(p => entities.Count(x => x.Equals(p)) > 1); 变量ans等于实体,其中实体中至少有两个相同的元素。 - Saeed Amiri
@Yustme,你能否发布你的代码?同时修改一下你的问题,删除掉“我取消了点赞”的内容。在你更新问题之前,我无法撤销它。给我留言吧。 - Saeed Amiri
1
我撤销了对你的踩,因为我认为你也给我踩了。var ans = this.pe.TPicture.Where(p => this.pe.TPicture.Count(x => x.HashCode ==p.HashCode) > 1); 当我说使用equal时,应该重写默认的equal函数,因为我不知道你的对象是什么。我说使用equal。上面的代码应该可以工作,如果有问题请告诉我 :D - Saeed Amiri
1
使用 Select 命令,执行 pe.TPicture.Where(p => this.pe.TPicture.Count(x => x.HashCode ==p.HashCode) > 1).Select(p => return new {p.ID, p.Value}) - Saeed Amiri
显示剩余9条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接