Linq to Sql:选择不同的行,同时忽略指定的列
如果我有一个查询/结果集如下...
from t1 in table1
join t2 in table2 on t1.ID equals t2.ID
join t3 in table3 on t2.ID equals t3.ID
select new MyClass()
{
ID = t1.ID,
Name = t2.Name,
Rank = t2.Rank,
City = t3.City
}
ID | Name | City | Rank
01 | Test | Fake | 876
01 | Test | Fake | 755
02 | Blah | Fake | 765
执行 .Distinct() 将返回所有 3 条记录,但如果我想要第一条和第三条记录并且不想从结果集中消除任何列怎么办?有没有一种方法可以指定在执行不同操作时忽略的列,或者显式包含在不同操作中,以便我可以执行类似的操作...
// pseudo code
.Distinct(o => o.Name.FirstOrDefault())
我认为可以使用 group by 来执行此操作,但这似乎会很慢而且很混乱,特别是当我需要对多列进行分组以避免排除太多行时。有什么想法吗?谢谢。
If I have a query/results set as follows...
from t1 in table1
join t2 in table2 on t1.ID equals t2.ID
join t3 in table3 on t2.ID equals t3.ID
select new MyClass()
{
ID = t1.ID,
Name = t2.Name,
Rank = t2.Rank,
City = t3.City
}
ID | Name | City | Rank
01 | Test | Fake | 876
01 | Test | Fake | 755
02 | Blah | Fake | 765
Doing a .Distinct() will return all 3 records, but what if I want the first and third record and don't want to eliminate any columns from my results set? Is there a way to specify columns to ignore when doing a distinct, or explicitly include in a distinct so that I could do something like this...
// pseudo code
.Distinct(o => o.Name.FirstOrDefault())
I think it's possible to do this using group by, but that seems like it would be slow and messy, especially if I needed to group on multiple columns in order to not exclude too many rows. Any ideas? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您无法指定用于确定
Distinct
相等性的投影。 (我有扩展方法来为 LINQ to Objects 执行此操作,但这是另一回事。)我建议您使用
GroupBy
,可能与First
结合使用:请注意,结果这可能不是确定性的 - 您正在获取每组的第一项,忽略排名 - 因此您可能会获得排名 876 的记录,或者在示例中您可能会获得排名 755 的记录。
我不确切知道这在 SQL 中会是什么样子 - 但您应该通过日志记录进行检查,然后运行查询分析器以查看成本会是什么样。
No, you can't specify a projection by which to determine equality for
Distinct
. (I have extension methods to do this for LINQ to Objects, but that's a different matter.)I suggest you use
GroupBy
, possibly in conjunction withFirst
:Note that the results of this may not be deterministic - you're taking the first item of each group, ignoring the rank - so you may get the record with rank 876 or you may get the one with rank 755 in your example.
I don't know exactly what this will look like in SQL - but you should check via logging, and then run the query profiler to see what the cost will be like.