LINQ到实体相当于SQL&QUOT的;顶(N)与领带"领带、实体、LINQ、QUOT

2023-09-03 02:07:30 作者:奶包妹纸ε

我一直searcing为 LINQ 相当于在的 SQL服务器的领带最近,我碰到一对夫妇的事情,这不可能坡口是有用的。

我知道这个问题有人问前并有一个公认的答案,但它不工作的方式有关系的确实的。采用该解决方案 GROUPBY()不会导致如预期的 TOP(3)领带考虑由一组数据对 {3 2 2 1 1 0} 的结果集将是 {3 2 2 1 1} ,它应该为 {3 2 2}

使用下面的示例数据(摘自this问题):

  CREATE TABLE人
(
    ID int主键,
    名称为nvarchar(50),
    分数浮动
)

INSERT INTO人VALUES(1,'汤姆',8.9)
INSERT INTO人VALUES(2,'杰里',8.9)
INSERT INTO人VALUES(3,'Sharti',7)
INSERT INTO人VALUES(4,'Mamuzi',9)
INSERT INTO人VALUES(5'卡马拉',9)
 

传统 OrderByDescending(P =&GT; p.Score)。取(3)将导致与 Mamuzi ,卡马拉< /骨节病>和之一的汤姆(或的杰里),其中应包括的的 BOTH 的

我知道有没有内置的是等效的,我已经找到一种方法来实现它。我不知道这是否是要做到这一点,打开替代解决方案的最佳途径。

解决方案

  VAR的查询=(距离中的q list.OrderByDescending(S =&GT; s.Score)。取(3) 。选择(S =&GT; s.Score).Distinct()
             从我的列表
             其中q == i.Score
             选择我).ToList();
 
一文了解 Text to SQL

编辑:

@Zefnus

我不知道在命令你想要的,但要更改顺序,你可以把一个排序依据(S => s.Score)之间的选择我和了ToList()

我没有检查什么SQL语句我的LINQ子句将产生的可能性。但是,你的答案是更好的,我认为。而你的问题也确实不错。我从来没有想过冠,在LINQ的关系。 ;)

基本上只需要顶端分数从第一清单中,并将它们与整个列表进行比较和i取只有那些分数它们等于第一列表的分数。

I have been searcing for LINQ equivalent of WITH TIES in sql server lately, I came across a couple things, which couldn't proove to be useful.

I know this question was asked before and has an accepted answer, but it doesn't work the way with ties does. The solution using GroupBy() doesn't result as expected for TOP(3) WITH TIES considering a data set consisting of {3 2 2 1 1 0} the result set will be {3 2 2 1 1} where it should be {3 2 2}

Using the following sample data (taken from this question):

CREATE TABLE Person
(
    Id int primary key,
    Name nvarchar(50),
    Score float
)    

INSERT INTO Person VALUES (1, 'Tom',8.9)
INSERT INTO Person VALUES (2, 'Jerry',8.9)
INSERT INTO Person VALUES (3, 'Sharti',7)
INSERT INTO Person VALUES (4, 'Mamuzi',9)
INSERT INTO Person VALUES (5, 'Kamala',9)

Traditional OrderByDescending(p => p.Score).Take(3) will result with: Mamuzi, Kamala and one of Tom (or Jerry) where it should include BOTH

I know there is no built-in equivalent of it and i've found a way to implement it. I don't know if it is the best way to do it and open for alternative solutions.

解决方案

var query = (from q in list.OrderByDescending(s => s.Score).Take(3).Select(s => s.Score).Distinct()
             from i in list
             where q == i.Score
             select i).ToList();

Edit:

@Zefnus

I wasn't sure in which order you wanted it but to change the order you can put a OrderBy(s => s.Score) between select i and ToList()

I don't have the possibility to check what sql statement my linq clause would produce. But your answer is much better i think. And your question was also really good. I never thought about top with ties in linq. ;)

Basically it only takes top 3 scores from the first list and compares them with the whole list and i takes only those scores which are equal to the scores of the first list.