anuj.rohila94
anuj.rohila94

Reputation: 105

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?

Upvotes: 3

Views: 1188

Answers (2)

codingbiz
codingbiz

Reputation: 26396

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460340

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")));

Upvotes: 2

Related Questions