在 LINQ 中选择 JOIN 后的所有列 [英] Select all columns after JOIN in LINQ

查看:24
本文介绍了在 LINQ 中选择 JOIN 后的所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,Table1Table2.我想执行一个左外连接:

I have two tables, Table1 and Table2. I want to perform, say, a left outer join:

var myOutput = from object1 in Table1
               join object2 in Table2
               on object1.Property1 equals object2.Property2 into Table3
               from output in Table3.DefaultIfEmpty()
               select new
                   {
                       object1.Property1,
                       object1.Property2,
                       //...
                       output.Property3,
                       output.Property4,
                       //...
                   };

如您所见,我想从结果表中选择两个对象的所有属性(连接时考虑的可枚举项包含某些类型的对象 - 这两种关系的这些属性不同).当然,我可以在匿名select中选择属性,如示例所示.

As you can notice, I want to select all the properties of both objects from the resulting table (the enumerables considered while joining contain the objects of certain types - these are different for both relations). Of course, I can select the properties in the anonymous select, as shown in the example.

我的问题是如何避免手动指定所有属性?我想要类似 SELECT * FROM TABLE3 的东西,其中 TABLE3 是结果关系(加入 TABLE1TABLE2 之后代码>).

My question is how to avoid specifying all the properties manually? I would like to have something like SELECT * FROM TABLE3, where TABLE3 is a resulting relation (after joining TABLE1 and TABLE2).

提前感谢您提供线索.

推荐答案

如果您想投影到扁平类型,您必须手动指定每个.你的另一个选择是让你的组合类型包含两个对象,对象自然会带来它们的属性.

You have to specify each manually if you want to project into a flattened type. Your other option is to just have your combined type contain both objects, and the objects will naturally bring along their properties.

select new 
{
    Object1 = object1,
    Object2 = output
};

你会像myObj.Object1.Property1myObj.Object2.Property4等一样使用它

仍然涉及一些手动工作的最后一个选项是定义一个适当的类型,并使用构造函数或构建器方法来完成将对象属性分割成扁平类型的工作.您仍然执行手动映射,但将其与查询逻辑隔离.

One final option that still involves some manual work is to define an appropriate type and have a constructor or a builder method that does the work of segmenting out your object properties into a flattened type. You still perform the manual mapping, but you isolate it from your query logic.

select new CombinedType(object1, output);
//or 
select builder.GetCombinedType(object1, output);

这篇关于在 LINQ 中选择 JOIN 后的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆