简体   繁体   中英

Combining join and select statement in LINQ to SQL

I'm using LINQ to SQL to perform select data from multiple tables after performing some computations on them. While performing the computations in the select statement, I would like to have the ability to reuse the results of a previous computation.

For instance:

var result = from da in DataA
             join db in DataB
             on da.colA = db.colB
             select new ClassA
             {
                fieldA = da.a + db.b,
                fieldB = fieldA + db.c
             };

Please note: fieldA and fieldB are fields in ClassA.

Now, LINQ to SQL doesn't allow the second statement:

fieldB = fieldA + db.c

So, I need to recalculate the value of fieldA to compute fieldB as:

fieldB = da.a + db.b + db.c

Is there any way for me to reuse the results of fieldA when I compute the value of fieldB in LINQ to SQL?

The let statement in LINQ is used to create temporary values that can be used later in a query. In LINQ to Objects, it essentially causes an intermediate Select that creates a new anonymous object containing the let value as well as the original values, so it isn't necessarily an efficiency improvement. In LINQ to SQL a nested SELECT is used to compute the intermediate expression.

var result = from da in DataA
             join db in DataB
             on da.colA = db.colB
             let fieldA = da.a + db.b
             select new ClassA
             {
                fieldA,
                fieldB = fieldA + db.c
             };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM