利用字串的StartsWith,EndsWith,Contains,讓LINQ有像sql指令like的功能

  • 38427
  • 0
  • LINQ
  • 2008-03-17

利用字串的StartsWith,EndsWith,Contains,讓LINQ有像sql指令like的功能

在小喵的blog裡有一篇文章,有人問到vb.net 和 c# 的LINQ寫法有一點不同

LINQ to Object初體驗(使用物件取代二維陣列作資料篩選)

小弟去網路找了一下資料...在C#的 like 其實有一個方法可以用

SqlMethods.Like的方法

在System.Data.Linq.SqlClient命名空間裡


參考網址:C#3.0入门系列(十一)-之In, Like操作

小弟做了一個使用string的StartsWith,EndsWith,Contains來達到like的功能

asp.net(c#)

環境:Visual Studio 2008 , .NET Framework 3.5

01 using System;
02 using System.Collections;
03 using System.Configuration;
04 using System.Data;
05 using System.Linq;
06 using System.Web;
07 using System.Web.Security;
08 using System.Web.UI;
09 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13 using System.Collections.Generic;
14 using System.Data.Linq.SqlClient;

15
16 public partial class LinqTest : System.Web.UI.Page
17 {
18     protected void Page_Load(object sender, EventArgs e)
19     {
20         //文字資料庫
21         string[] StrDB = { "Puma", "BlueShop", "Microsoft", "Linq","Ling","Luma" };
22
23         //like "Li%"
24         IEnumerable<string> StrSelete = from str in StrDB where str.StartsWith("Li") orderby str select str;
25         /*
26         result:
27         Ling
28         Linq
29         */

30
31         //like "%ma"
32         //IEnumerable<string> StrSelete = from str in StrDB where str.EndsWith("ma") orderby str select str;
33         /*
34         result:
35         Luma
36         Puma
37         */

38
39         //like "%i%"
40         //IEnumerable<string> StrSelete = from str in StrDB where str.Contains("i") orderby str select str;
41         /*
42         result:
43         Ling
44         Linq
45         Microsoft
46         */

47
48         //列出查詢結果
49         foreach (string item in StrSelete)
50         {
51         Response.Write(item + "<br/>");
52         }

53     }

54 }