Linq 单列分组不工作

发布于 2024-11-25 22:11:47 字数 331 浏览 2 评论 0原文

我是 Linq 新手,所以请原谅我的无知,但我需要按表中的列进行分组,然后仅返回该列。我最终应该得到一个唯一数字的列表。

这是我的 Linq

from r in myTable
group r.UserID by r.UserID

,但在 Linq pad 中它接近我想要的,但每个相似的 ID 都有一个“密钥”或所有相同 id 分组在一起的东西,包含在结果中。我只想要一个数字列表。

这就是完美的 SQL。

SELECT UserID FROM myTable
GROUP BY UserID

I'm a Linq noob so please excuse my ignorance but I need to group by a column in a table and then return just that column. I should end up with a list of unique numbers.

This is my Linq

from r in myTable
group r.UserID by r.UserID

but in Linq pad it gets close to what I want but each similar ID has a 'key' or something with all the same ids grouped together, included in the results. I just want a list of numbers.

this is the SQL that is perfect.

SELECT UserID FROM myTable
GROUP BY UserID

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独岁月 2024-12-02 22:11:47

为什么不呢

var userIds = myTable.Select(r => r.UserId).Distinct();

,或者,如果您更喜欢查询语法,

var userIds = (from r in myTable select r.UserId).Distinct();

如果您只想使用组 ID,则不需要分组。

Why not

var userIds = myTable.Select(r => r.UserId).Distinct();

or, if you prefer query syntax

var userIds = (from r in myTable select r.UserId).Distinct();

Grouping is unnecessary if you're only going to use the group ids.

不弃不离 2024-12-02 22:11:47

我认为您真正想要的 SQL

SELECT DISTINCT UserID FROM myTable

Group by 正在做同样的事情,作为您对它的特定用法的副作用。

我相信相同的语法可能在 LINQ 语句语法中起作用,dlev 所说的会起作用,尽管我不确定它是否正确转换为 SQL,因为它不在语句语法中。

如果我错了,L2S 会正确转换他的版本,那么 dlev 一定会固定它。

I think the actual SQL you want is

SELECT DISTINCT UserID FROM myTable

Group by is doing the same thing as a side effect of your particular usage of it.

I believe the same syntax is likely functional in LINQ statement syntax, what dlev said would work though I'm not certain it gets converted to the SQL properly as it's not in the statement syntax.

If I'm mistaken and L2S will properly convert his version then by all means dlev's got it pegged.

笔芯 2024-12-02 22:11:47

您的查询为您提供了组。如果你只想要钥匙,你应该得到钥匙。

IQueryable<IGrouping<int, Record>> query1 =
  from r in myTable
  group r.UserID by r.UserID;

IQueryable<int> query2 =
  from r in myTable
  group r.UserID by r.UserID into g
  select g.Key;

  //alternatively
query1 = myTable.GroupBy(r => r.UserID);
query2 = query1.Select(g => g.Key);

Your query gives you groups. If you just want keys, you should get keys.

IQueryable<IGrouping<int, Record>> query1 =
  from r in myTable
  group r.UserID by r.UserID;

IQueryable<int> query2 =
  from r in myTable
  group r.UserID by r.UserID into g
  select g.Key;

  //alternatively
query1 = myTable.GroupBy(r => r.UserID);
query2 = query1.Select(g => g.Key);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文