如何使用C#在Linq查询中设置动态Where子句

时间:2012-10-13 09:40:58

标签: c# asp.net

我有这个代码: -

DataSet ds = new DataSet();

String s = "StudentID = 5 Or StudentID=6"; 
var result = from r in ds.table[0].AsEnumerable() where s.ToString() select r;

如何从中获取数据?

2 个答案:

答案 0 :(得分:2)

为什么不能使用ID列表?

//assuming you have text and that's the reason
var txtIDs = "5,6";
var IDs = txtIDs.Split(',').Select(s => int.Parse(s));

var rows = from r in ds.Tables[0].AsEnumerable()
           where IDs.Any(id => r.Field<int>("ID")==id)
           select r;

或方法语法:

var rows = ds.Tables[0].AsEnumerable()
           .Where(r => IDs.Contains(r.Field<int>("ID")));

答案 1 :(得分:0)

试试这个

var result = ds.Tables[0].AsEnumerable().Where(row => row["StudentID"].ToString() == "5" || row["StudentID"].ToString() == "6")

var result = from r in dx.AsEnumerable() 
             where r["StudentID"].ToString() == "5" || r["StudentID"].ToString() == "6" 
             select r; 

你可以试试这个

DataTable dt = result.CopyToDataTable(); //for both code above