dotnetdevcsharp
dotnetdevcsharp

Reputation: 3980

Building where statement dyamically

I have a list where I wish to add items to dyanmically in the where clause if I dont have a user id at present the linq will fall over.

List<ScreenermissionsForSearch> _screen = new List<ScreenermissionsForSearch>();
_screen= _security.GetScreenermissionsForSearch();

gridControl1.DataSource = _screen.Where(w => w.Code ==
Convert.ToInt32(txtUserId.Text) || w.ScreenName ==dbscreenanme.Text).ToList();

this.gridView1.Columns[0].Width = 50;
this.gridView1.Columns[1].Width = 100;

So I need some wway of being able to append to the where clause checking if the string is null or not first or am I not doing this right in the frist place?.

Edit to show clairty Here it is just listing them all when i want it to only show provider if user id is empty.

enter image description here

It works here and shows fine as should do but its not for the other condition enter image description here

New Code

 _screen= _security.GetScreenermissionsForSearch();
        gridControl1.DataSource = _screen.Where(w => string.IsNullOrEmpty(txtUserId.Text)  || w.ScreenName == dbscreenanme.Text).ToList();
        this.gridView1.Columns[0].Width = 50;
        this.gridView1.Columns[1].Width = 100;

Upvotes: 1

Views: 58

Answers (1)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

Add this condition to where clause string.IsNullOrEmpty(txtUserId.Text) and change the condition;

gridControl1.DataSource = _screen.Where(w =>
    (string.IsNullOrEmpty(txtUserId.Text) || w.Code == Convert.ToInt32(txtUserId.Text)) &&
    w.ScreenName == dbscreenanme.Text)).ToList();

If you don't want to get result when parsing is failed try following code;

gridControl1.DataSource = _screen.Where(w =>
    w.Code == int.TryParse(txtUserId.Text,out var val) ? val : -1 &&
    w.ScreenName == dbscreenanme.Text)).ToList();
var entity = Context.Parents.Include(x => x.Name).ToList();

Upvotes: 1

Related Questions