0

Can someone convert the following simple SQL statement into LINQ? The StudentID is of type int.

select * from Student where studentId like '%1001%';

Thank you!

Keith
  • 5,311
  • 3
  • 34
  • 50
rk1962
  • 1,713
  • 3
  • 24
  • 29

3 Answers3

0
 ctx.Student.Where(x => x.StudentId.Contains("1001"))

It's strange that you have an ID of string type. Use int instead.

O, sorry, I see now, you wrote that ids are ints. In that case you cannot use like in SQL. It doesnt make sense. You must convert int to string first.

ctx.Student.Where(x => x.StudentId.ToString().Contains("1001"))
pero
  • 4,169
  • 26
  • 27
  • It works! I tried this before and it did not work because I forgot to use quotes in "1001". Thank you so much for your quick response. – rk1962 Jun 23 '11 at 22:01
0

Use the Contains operator:

from s in Student
where s.studentId.ToString().Contains("1001")
select s;
Lucent Fox
  • 1,737
  • 1
  • 16
  • 24
  • It is giving the following error: 'int' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource)' has some invalid arguments – rk1962 Jun 23 '11 at 21:51
  • Change it to: where s.studentId.ToString().Contains("1001") I was assuming since you were comparing a column to a string in your original query that the column itself was a string. Honestly, this sort of query goes against what I would consider good programming practices with regards to the use of primary keys; it makes me think that there may be a better way to accomplish what you want that will give you less headaches down the road. You may want to investigate. – Lucent Fox Jun 23 '11 at 22:02
  • Just reread the OP and noticed that it stated that it was an int, my bad. – Lucent Fox Jun 23 '11 at 22:04
  • Actually, the StudentID column is of type int. I wanted to return all rows that matches 1001. I belive this is the only simple way you can retrieve all rows that contains 1001. Let me know if my understanding is wrong. Thank you! – rk1962 Jun 23 '11 at 22:06
0

Try this:

db.Students.Where(s => s.StudentID.ToString().Contains("1001"))
Keith
  • 5,311
  • 3
  • 34
  • 50