Rondakay
Rondakay

Reputation: 160

Conditional filter on list

var dbRecords = (from c ...... query removed).Where(c => c.BNumber.Contains(bnum)).ToList();

// At this point dbRecords contains 596 records

int chkCount = 0;

// I have a series of checkboxes for filtering of the query

foreach (ListItem c in chklColumns.Items)
{
    if (c.Selected == true)
    {
        chkCount++;
    }
    if (chkCount > 0)
    {
        foreach (ListItem x in chklColumns.Items)
        {
            var gridKey = "Grp" + x.Value;

            if (x.Selected)
            {
               if (gridKey == "GrpSOS")
               {
                   dbRecords.Where(p => p.SOSEnabledYN == true);
               }
               if (gridKey == "GrpMOB")
               {
                   dbRecords.Where(p => p.ZMobileEnabledYN == true);

                   // If this filter were applied then my resultset would be 276 records
                   // I step through and hit this code but it does not seem to be affecting the dbRecords list
               }
               if (gridKey == "GrpPHO")
               {
                   dbRecords.Where(p => p.PhoneMonitorEnabledYN == true);
               }
           }
       }
   }

WebDataGrid1.DataSource = dbRecords;
WebDataGrid1.DataBind();

After filtering with the Where statement for each checkbox I bind to the grid - but it is always the same count of records - almost like the filters were not being applied. Why is the dbRecords not being adjusted by the Where statements?

Upvotes: 0

Views: 2486

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Where() returns a new filtered list, it does not not modifies the original list so you need to store the filtered list like this:

dbRecords = dbRecords.Where(p => p.SOSEnabledYN == true);

EXAMPLE:

List<User> myUsers = New List<User>();
//fill the list myUsers with some User object
List<User> activeUsers = myUsers.Where(u => u.Active == True);
//the activeUsers list will contain only active users filtered from list of all users 

Upvotes: 3

Related Questions