【问题标题】:get duplicates from a table using linq to entities使用 linq 到实体从表中获取重复项
【发布时间】:2010-11-01 00:15:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# linq-to-entities


    【解决方案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]);
                        }
                }
    

    【讨论】:

    • 这会选择整行吗?因为只获取哈希码不是我想要的。不应该是“来自 r in this.entities.table where r.hashcode .......”吗?
    • @Yustme,我写了Equals 来概括它,您可以将其用作return r.hashcode == x;,您是否投了反对票?如果是这样,请先问为什么会这样然后那样做。
    • 你能写entities.Where(p =&gt; entities.Count(x =&gt; x.hashcode == p.hashcode) &gt; 1);很难吗?
    • Nothing 我删除了我为你留下的反对票,因为我认为你给我留下了反对票,var ans = this.pe.TPicture.Where(p =&gt; this.pe.TPicture.Count(x =&gt; x.HashCode ==p.HashCode) &gt; 1); 当我说使用相等时你应该覆盖默认的equal 函数,因为我没有知道你的对象是什么我说使用相等。如果不告诉我,上述内容应该仔细工作:D
    • 使用Select命令,执行pe.TPicture.Where(p =&gt; this.pe.TPicture.Count(x =&gt; x.HashCode ==p.HashCode) &gt; 1).Select(p =&gt; return new {p.ID, p.Value})
    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多