简体   繁体   中英

how to set dynamic Where Clause in Linq Query with C#

I have this code:-

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;

How to get data from this?

Why can't you use a list of ID's?

//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;

or in method syntax:

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

Try this

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

or

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

You can try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM