简体   繁体   English

Linq查询嵌套选择+不同

[英]Linq Query Nested select + distinct

I'm having a really hard time converting this query to LINQ. 我很难将此查询转换为LINQ。

select fk, count(*)
from (
    select distinct fk, attribute1, attribute2
    from table
) a
group by fk
having count(*) > X

I need each distinct combination of fk, attr1, attr2 grouped by fk only where count is bigger than x (parameter). 我只需要在计数大于x(参数)的情况下按fk分组的fk,attr1,attr2的每个不同组合。

Any ideas? 有任何想法吗?

First, create your nested query: 首先,创建您的嵌套查询:

var query= db.Table.Select(e=>new {e.FK, e.Attribute1, e.Attribute2}).Distinct();

After that, you can do this: 之后,您可以执行以下操作:

int x=10;
var result= from e in query
            group e by e.FK into g
            let count=g.Count()
            where count>x
            select new{FK=g.Key, Count=count};

When you call, for example, the ToList method, is when those queries are going to be executed against your DB and the resulted elements are going to be loaded into the memory. 例如,当您调用ToList方法时,这些查询将针对您的数据库执行,并且结果元素将被加载到内存中。

var elements=result.ToList();

Merging all, you could also do this: 合并所有内容,您也可以这样做:

int x=10;
var elements=(from e in db.Table.Select(e=>new {e.FK, e.Attribute1, e.Attribute2}).Distinct()
             group e by e.FK into g
             let count=g.Count()
             where count>x
             select new{FK=g.Key, Count=count}).ToList();

You'll have to implement IComparable , IComparer or pass IEqualityComparer or some other way to ensure Distinct() works across your class' properties, but here's the essential linq: 您必须实现IComparableIComparer或传递IEqualityComparer或其他方法来确保Distinct()在整个类的属性中均有效,但这是基本的linq:

var result = (from t in tableList.Select(t => new { fk, attr1, attr2 }).Distinct()
              group t by t.fk into g
              select new { fk = g.Key, Count = g.Count() })
             .Where(t => t.Count > X)
             .ToList();

this uses an anonymous type as the equivalent of 'select fk, attribute1, attribute2' but that may make it harder to implement Distinct(). 这使用了与“ select fk,attribute1,attribute2”等效的匿名类型,但可能使实现Distinct()更加困难。

By default Distinct() does an object-level compare (are the two instances the same instance) rather than a value-level compare (do they have the same value). 默认情况下, Distinct()进行对象级比较(两个实例是同一实例),而不是值级比较(它们具有相同的值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM