.net - 使用 LINQ 选择和组合对象的正确方法是什么?

标签 .net linq

这是我经常遇到的一种情况:我有 Parent 和 Child 对象,而 Child 对象有一个 Parent 属性。我想运行一个查询来获取子对象并将每个对象连接到正确的父对象:

Dim db = New DataContextEx()

get the children, along with the corresponding parent
Dim Children = From x In db.ChildTable
                Join y In db.ParentTable
                On x.ParentId Equals y.Id
                Execute x.Parent = y       <-- pseudocode
                Select x   

伪代码显示了我想要完成的任务:返回子对象 x 但在执行(假) Execute 语句之后使用代码。我可以想到很多方法来实现最终目标,但它们都有更多的代码行和/或临时对象或函数的创建,我觉得这些方法很不雅观。 (注意这是 VB.NET 语法,但它不是 VB 语法问题,因为 AFAIK C# 也会有同样的问题。)

那么做我想做的最干净的方法是什么?

编辑 :人们问我正在使用什么 ORM,但这确实是一个普通的 LINQ 问题;我不想将其转换为要在服务器上运行的逻辑,我只是​​想要一些语法糖在服务器上运行查询后运行代码客户端。

最佳答案

您可以在投影结果时使用匿名类型。 C# 示例:

var items = from x In db.ChildTable
            join y In db.ParentTable on x.ParentId equals y.Id
            select new { Child =x , Parent=y };

然后分配父属性。
foreach(var item in items)
{
    item.Child.Parent = item.Parent;
}

return items.Select(item => item.Child);

此外,您可能想为此使用一些 ORM 解决方案,而不是自己滚动解决方案。

关于.net - 使用 LINQ 选择和组合对象的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8659647/

相关文章:

c# - ComboBoxItem MouseEnter 事件未触发

.net - IIS 无法创建 .net 3.5 应用程序池

asp.net - 如何在 .net web api Controller 中读取多部分表单数据

c# - 从 SQL 数据库中删除

c# - 如何将 Expression<Func<TEntity, bool>> 映射到 Expression<Func<TDbEntity, bool>>

c# - 如何将带有对象的字典转换为该类型的列表?

.net - 安排 Azure 媒体服务中的实时流媒体 channel 在特定时间以编程方式启动

.net - 是否有任何 .net 等同于 Rails 固定装置?

c# - 搜索列表并根据匹配的索引值获取项目

c# - InvalidOperationException : type 'System.String' referenced from scope '' , 但未定义