2010-10-12 71 views

回答

29

你可以使用SqlMethods.Like(matchExpression,pattern)

var results = from c in db.costumers 
       where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName) 
       select c; 

使用这种方法的LINQ以外的SQL总会抛出NotSupportedException异常。

+0

我没有时间用这个方法来解决问题:其中SqlMethods.Like(s.Email,id +“%”)通过一个错误(是的,我使用System.Data.Linq.SqlClient;我更改为在哪里s.Email.Contains(id)即使那是不一样的,我可以使它改变EndsWith – 2015-10-20 17:29:30

26

尝试使用string.Contains()与EndsWith组合。

var results = from c in db.Customers 
       where c.FullName.Contains (FirstName) && c.FullName.EndsWith (LastName) 
       select c; 
+0

我比SqlMethods更喜欢这个 – 2015-10-20 17:29:56

+2

与'like'查询相反,这不区分大小写。 – 2016-05-18 11:56:04

+0

如果使用实体框架,此查询将转换为SQL LIKE语句,因此其大小写敏感性取决于列/表/ db的排序规则。 – 2017-09-14 09:54:13

2
where c.FullName.Contains("string") 
1

您可以使用包含:

string[] example = { "sample1", "sample2" }; 
var result = (from c in example where c.Contains("2") select c); 
// returns only sample2 
11

尝试这样

var results = db.costumers.Where(X=>X.FullName.Contains(FirstName)&&(X=>X.FullName.EndsWith(LastName)) 
          .Select(X=>X); 
+3

为什么不使用'&&'运算符,而不是双Where子句? – Max 2013-12-04 13:33:24

+0

@MaxMommersteeg:谢谢,更新 – 2013-12-16 09:58:54

+0

@max为什么不是2 where子句?如果每个where子句都在它自己的行上,那么如果有很多长条件,它会使代码更具可读性。 – Phil1970 2016-08-04 16:28:11

3
String [] obj = (from c in db.Contacts 
          where c.FirstName.StartsWith(prefixText) 
          select c.FirstName).ToArray(); 
      return obj; 

StartsWith()和的endsWith()可以帮助你在这里有很多。如果你想在字段间找到数据,那么可以使用Contains()。

0

var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();

用户可以在LINQ的使用类似的查询,并填写学生模型。

+0

如果输入来自用户,则容易引发SQL注入... – Phil1970 2016-08-04 16:30:09