LINQ to SQL – using Linq for SQL ‘Like’ statement
I’m really enjoying using LING to SQL, mostly because of the new .NET framework 3.5 LINQ features.
My latest find was ‘how do I make a ‘LIKE’ query using LINQ to SQL’ ?
Well, it was almost too intuitive
FSDALDataContext dc = new FSDALDataContext(connectionString); var pilotStats = from p in dc.CurrPilotStats where p.PilotName.Contains(pilotName) orderby p.Missions descending select p; return pilotStats.ToList();
In the example above the equivalent SQL is
FROM tblCurrPilotStats WHERE (PilotName LIKE @ParamPilotName) ORDER BY Missions DESC"
If you are wanting a startswith or endswith, it’s the same syntax p.PilotName.Startswith(…)
A bit off subject, but I can approach queries with the syntax above, or use lamba:
FSDALDataContext dc = new FSDALDataContext(connectionString); var g = dc.MisAirSummaries.Where(air => air.MissionNum == decimal.Parse(missionID)); return g.ToList();
Notice both statements have the ‘ToList()’ – the actual query is executed at that point.