3

I have the following SQL statement

SELECT 
    c.CorpSystemID, c.SystemName  , 
    case when a.TaskItemID is NULL then 'false' else 'true' end as Assigned
FROM CorpSystems c 
LEFT OUTER JOIN
     (SELECT CorpSystemID, TASKItemID 
      FROM AffectedSystems 
      where TASKItemID = 1) a ON c.CorpSystemID = a.CorpSystemID

Can anyone please help me to convert this statement to LINQ?

Thank you.

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
Yuri
  • 2,820
  • 4
  • 28
  • 40
  • 2
    Have you tried something by yourself? (https://www.google.ca/search?ix=hca&sourceid=chrome&ie=UTF-8&q=linq+to+sql+examples) – Francis P Apr 11 '12 at 13:13
  • 2
    Showing you the LINQ query is only somewhat useful. You need to gather the context either in Memory or via a remote LINQ provider like LINQ to SQL or entity framework to make the LINQ function in place of the T-SQL. This is why its useful to give it a shot yourself first. – P.Brian.Mackey Apr 11 '12 at 13:20

2 Answers2

3

Ok so assume you've got a list of your CorpSystem objects in a variable called Corpsystems and a list of your AffectedSystem objects in a variable called AffectedSystems. Try the following:

Edit: For a join on all Affected Systems, try this:

var matches = from c in CorpSystems
              join a in AffectedSystems on c.CorpSystemId equals a.CorpSystemId into ac
              from subSystem in ac.DefaultIfEmpty()
              select new
                     {
                         c.CorpSystemId,
                         c.SystemName,
                         Assigned = subSystem != null && subSystem.TaskItemId != null
                     };

Or for just AffectedSystems that have a TaskItemId of 1:

var matches = from c in CorpSystems
              join a in AffectedSystems.Where(as => as.TaskItemId == 1)
                  on c.CorpSystemId equals a.CorpSystemId into ac
              from subSystem in ac.DefaultIfEmpty()
              select new
                     {
                         c.CorpSystemId,
                         c.SystemName,
                         Assigned = subSystem != null && subSystem.TaskItemId != null
                     };
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
1

See the answers to the following SO question SQL to LINQ Tool, assuming that you do not want to go through the process by hand.

Community
  • 1
  • 1
Joshua Drake
  • 2,704
  • 3
  • 35
  • 54