在 Linq 中选择多列时,在列上选择 DISTINCT
我从表中选择多列(id、名称)。我想取回具有不同名称的记录。我想知道如何在 LINQ 中执行此操作。
以下代码返回一个 Dictionary
return db.CourseTypes
.Select(ct => new { ct.Id, ct.Name})
.AsEnumerable()
.ToDictionary(kvp => kvp.Id.ToString(), kvp => kvp.Name);
}
如何确保获取“名称”列中具有不同值的记录?
I'm selecting multiple columns from a table (id, name). I would like to get back records with distinct name. I'm wondering how to do this in LINQ.
The following code returns a Dictionary<string,string>
return db.CourseTypes
.Select(ct => new { ct.Id, ct.Name})
.AsEnumerable()
.ToDictionary(kvp => kvp.Id.ToString(), kvp => kvp.Name);
}
How can I make sure to get back records with distinct values in the 'Name' column?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
比 StriplingWarrior 稍微简单的方法(我认为),问题也稍微少一些:
请注意,这假设您的 ID 也是唯一的 - 如果两个不同的名称具有相同的 ID,则
ToDictionary
将会失败。另请注意,如果您有多个同名 ID,则假设您并不真正关心地图中的哪个 ID。如果你想确保它是(比如说)你可以做的最早的名称:
现在这可能会在错误的点进行 Queryable 到 Enumerable 的转换,所以你可能想要:
这更有可能一次性完成数据库中的所有排序等...我认为...不过值得检查日志。
A slightly simpler approach than StriplingWarrior's (I think) and with slightly fewer issues:
Note that this assumes your IDs are also unique - if two different names have the same ID,
ToDictionary
will fail.Also note that if you've got multiple IDs with the same name, it's assuming you don't really care which one is in the map. If you want to make sure it's (say) the earliest name you could do:
Now it's possible that that will do the Queryable to Enumerable transition at the wrong point, so you might want:
That's more likely to do all the ordering etc within the database in one go... I think... it's worth checking the logs though.