LINQ to SQL語句(15)之String
系列文章導航:
LINQ to SQL語句(2)之Select/Distinct
LINQ to SQL語句(3)之Count/Sum/Min/Max/Avg
LINQ to SQL語句(6)之Group By/Having
LINQ to SQL語句(7)之Exists/In/Any/All/Contains
LINQ to SQL語句(8)之Concat/Union/Intersect/Except
LINQ to SQL語句(9)之Top/Bottom和Paging和SqlMethods
LINQ to SQL語句(12)之Delete和使用Attach
LINQ to SQL語句(14)之Null語義和DateTime
LINQ to SQL語句(19)之ADO.NET與LINQ to SQL
字符串(String)
LINQ to SQL支持以下String方法。但是不同的是默認情況下System.String方法區分大小寫。而SQL則不區分大小寫。
1.字符串串聯(String Concatenation)
var q = from c in db.Customers select new { c.CustomerID, Location = c.City + ", " + c.Country };
語句描述:這個例子使用+運算符在形成經計算得出的客戶Location值過程中將字符串字段和字符串串聯在一起。
2.String.Length
var q = from p in db.Products where p.ProductName.Length < 10 select p;
語句描述:這個例子使用Length屬性查找名稱短于10個字符的所有產品。
3.String.Contains(substring)
var q = from c in db.Customers where c.ContactName.Contains("Anders") select c;
語句描述:這個例子使用Contains方法查找所有其聯系人姓名中包含“Anders”的客戶。
4.String.IndexOf(substring)
var q = from c in db.Customers select new { c.ContactName, SpacePos = c.ContactName.IndexOf(" ") };
語句描述:這個例子使用IndexOf方法查找每個客戶聯系人姓名中出現第一個空格的位置。
5.String.StartsWith(prefix)
var q = from c in db.Customers where c.ContactName.StartsWith("Maria") select c;
語句描述:這個例子使用StartsWith方法查找聯系人姓名以“Maria”開頭的客戶。
6.String.EndsWith(suffix)
var q = from c in db.Customers where c.ContactName.EndsWith("Anders") select c;
語句描述:這個例子使用EndsWith方法查找聯系人姓名以“Anders”結尾的客戶。
7.String.Substring(start)
var q = from p in db.Products select p.ProductName.Substring(3);
語句描述:這個例子使用Substring方法返回產品名稱中從第四個字母開始的部分。
8.String.Substring(start, length)
var q = from e in db.Employees where e.HomePhone.Substring(6, 3) == "555" select e;
語句描述:這個例子使用Substring方法查找家庭電話號碼第七位到第九位是“555”的雇員。