本文章转载:http://www.cnblogs.com/guyun/archive/2012/10/18/2729888.html
需求是这样的,有一张表tbl(Key[int],Value[string]),数据存储如下:
Key | Value |
1 | -a-b- |
2 | -a- |
3 | -c-e- |
4 | -f-g- |
现在的目的是要从tbl表中取出所有Value字段的值和List的值匹配的记录。本地有个List<string>{"a","b","c"};
传统的T-SQL写法是:select * from tbl where Value like '%a%' or Value like '%b%' or Value like '%c%' 如何用linq实现呢?
我第一个想到的是这样的:
var query=from q in tbl select q;
foreach(var item in list) { query=query.Where(r=>r.Value.Contains(item)); }
但是这样做生成的T_SQL语句是:select * from tbl where Value like '%a%' and Value like '%b%' and Value like '%c%'
同样也可以像SQL语句这样:select * from tb1 as a inner join tb2 as b on a.value like "%'+b.value;
唉,真蛋疼,百度了好多全都无解,最后看到了一篇帖子,给了我点启发,帖子链接如下:http://social.msdn.microsoft.com/Forums/de-DE/238/thread/b8ea22a7-f733-4ff5-8333-0dd3fe558076
经过思路整理,最终代码如下:
class Program { static void Main(string[] args) { var dt = new DataTable(); dt.Columns.Add("Key", typeof (int)); dt.Columns.Add("Value", typeof (string)); dt.Rows.Add(1, "-a-b-"); dt.Rows.Add(2, "-a-"); dt.Rows.Add(3, "-c-e-"); dt.Rows.Add(4, "-f-g-"); var list = new List<string> {"a", "b", "c"}; var query = from q in dt.AsEnumerable() from t in list where q.Field<string>("Value").Contains(t) select q; var vdt = query.Distinct().CopyToDataTable(); foreach (DataRow dr in vdt.Rows) { Console.WriteLine(dr["Key"] + "\t" + dr["Value"]); } } }
大功告成,输出结果如下:
1 -a-b-
2 -a-
3 -c-e-