0

I want to know a query in linq which is equivalent to below:

select t1.*, (select columname from table2 t2 where id = 2)
from table1 t1
Magnus
  • 43,221
  • 7
  • 76
  • 112
Tejashri Patange
  • 173
  • 1
  • 4
  • 19
  • See if this helps https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations – SoConfused Aug 21 '18 at 14:24
  • This might be better https://stackoverflow.com/questions/12859536/simple-select-query-in-linq – SoConfused Aug 21 '18 at 14:27

1 Answers1

0

Following my SQL to LINQ Recipe, but with a slight twist for the sub-query being in the select:

var ans = from t1 in table
          select new {
              t1,
              columnname = (from t2 in table2
                            where id == 2
                            select columnname).FirstOrDefault()
          };

Note this will be sent to SQL as one query. This is one case where putting the sub-query in another variable will cause LINQ to send two SQL queries instead. SQL requires an (implied) First on the sub-query, but you could leave it off if you don't mind columnname being an IEnumerable that potentially has multiple values.

NetMage
  • 24,279
  • 3
  • 31
  • 50