Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

c# - Select all columns after JOIN in LINQ

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,
                       //...
                   };

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.

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).

Thanks in advance for the clues.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
};

And you would work with it like myObj.Object1.Property1, myObj.Object2.Property4, etc.

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...