有没有办法在 LINQ 查询语法中使用 Distinct?
有没有办法重写:
var tbl = ds.TABLES;
var q = from c in tbl
select c.TABLE_TYPE;
string s = "";
foreach (var item in q.Distinct())
{
s += "[" + item + "]";
}
MessageBox.Show(s);
以便 Distinct() 调用位于 LINQ 查询中?
Is there way to rewrite:
var tbl = ds.TABLES;
var q = from c in tbl
select c.TABLE_TYPE;
string s = "";
foreach (var item in q.Distinct())
{
s += "[" + item + "]";
}
MessageBox.Show(s);
So that the Distinct() call is in the LINQ query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
语言集成查询语法中没有
Distinct()
方法语法。您可以做的最接近的事情就是移动当前呼叫:There is no
Distinct()
method syntax in the language integrated query syntax. The closest you could do would be to move the current call:LINQ 中的
Distinct
扩展方法没有等效的查询语法。请参阅 https:// learn.microsoft.com/en-us/archive/blogs/charlie/linq-farm-using-distinct-and-avoiding-lambdas 了解有关原因的更多信息。
The
Distinct
extension method in LINQ does not have a query syntax equivalent.See https://learn.microsoft.com/en-us/archive/blogs/charlie/linq-farm-using-distinct-and-avoiding-lambdas for additional information as to why.
如果您在选择后放置不同的值,VB 就有此功能。
VB has this functionality if you place the distinct after select.
您可以捕获 HashSet 并将 where 子句放在 select 之前:
You may capture HashSet and put where clause before select:
在为 LINQ 寻找 Distinct 函数时,发现这个问题并意识到它不存在,我的解决方法是使用 GroupBy()。
明显的问题是,distinct-set 不包含所有数据(假设您有三个字段,但只想在两个字段上进行区分,而缺少最后一个字段的值,但是,话又说回来,t-sql 中的 DISTINCT工作方式相同)。
LINQ 代码(因此转储):
LINQ 转储结果
In the search for a Distinct-function for LINQ upon finding this question and realizing it doesn't exist, my workaround is by using GroupBy().
The obvious problem is that the distinct-set doesn't contain all the data (say you have three fields but only want to distinct on two fields missing out on the value for the last field, but, then again, DISTINCT in t-sql works the same way).
LINQ-code (hence the Dump):
LINQ-dump result