如何使用 linq 从父对象检索孙对象
我有几个家长>儿童>我的数据库模式中的孙子关系。通常,我有父母,我想要一些关于孙子的信息。例如,我有一个用户,他拥有一系列社交网络,其中包含许多朋友。我发现自己一遍又一遍地编写这段代码。
var friends = new List<Friend>();
foreach (var socialNetwork in user.UserSocialNetworks)
{
foreach (var friend in socialNetwork.Friends)
{
friends.Add(friend);
}
}
有没有更优雅的方法来使用 linq 来做到这一点?
我真正想做的是“user.Friends”,但我必须在朋友表中添加一个指向 user 的外键,这听起来不太对劲。看起来是这样的:
User {Id,..}
SocialNetwork {Id, UserId, ...}
Friend {Id, SocialNetworkId, UserId, ... }
想法?
I have several parent > child > grandchild relationships in my db schema. Usually, I have the parent and I want some information about the grandchildren. For example, I have a user who has a collection of social networks which have collections of friends. I find myself writing this code over and over again.
var friends = new List<Friend>();
foreach (var socialNetwork in user.UserSocialNetworks)
{
foreach (var friend in socialNetwork.Friends)
{
friends.Add(friend);
}
}
Is there a more elegant way to do this with linq?
What I'd really like to be able to do is "user.Friends" but I'd have to put a foreign key to user in the friend table and that doesn't smell right. Here is what that would look like:
User {Id,..}
SocialNetwork {Id, UserId, ...}
Friend {Id, SocialNetworkId, UserId, ... }
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将代码作为
User
类上的方法编写一次:或者,您可以只使用
SelectMany()
:You can write the code just once as a method on the
User
class:Alternatively, you can just use
SelectMany()
:我知道这一点,但我最近遇到了同样的事情,另一种选择就是以相反的方式解决它。不要从用户开始并向下钻取,而是从朋友开始并根据父母(或祖父母)进行过滤。为此,您需要用户的 ID。当层次结构变得更深时,我发现这更清晰。像这样的东西:
I know this old, but I've recently faced the same thing, and an alternative is to go about it the opposite way. Instead of starting at user and drilling down, start at Friend and filter based on the parent (or grandparent). You would need the user's Id for this. When the hierarchy gets deeper, I find this more legible. Something like: