Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to study MVC. I have an EDMX class which represents an Employee entity which has 5 properties ID,Name,Email,Address & IsActive.

I am trying to sort the employee list using linq. The sorting field is dynamically set based on which column is clicked in list page.

This is the code i have written

C#
public List<Employee> GetEmployees(bool includeInActive = false, string searchKey = "", string sortingField = "ID", string sortingDirection = "asc")
       {
           DB_Arjun objDB_ArjunEntities;
           try
           {
               objDB_ArjunEntities = new DB_Arjun();
               List<Employee> lstEmployee = new List<Employee>();

               if (string.IsNullOrWhiteSpace(searchKey))
               {
                   if (sortingDirection != "asc")
                   {
                       var tmpList = from employee in objDB_ArjunEntities.Employees.ToList()
                                     orderby sortingField descending
                                     select employee;

                       foreach (Employee emp in tmpList.ToList())
                       {
                           if (includeInActive)
                               lstEmployee.Add(emp);
                           else if (!includeInActive && emp.IsActive == true)
                               lstEmployee.Add(emp);
                       }
                   }
                   else
                   {
                       var tmpList = from employee in objDB_ArjunEntities.Employees.ToList()
                                     orderby sortingField
                                     select employee;

                       foreach (Employee emp in tmpList.ToList())
                       {
                           if (includeInActive)
                               lstEmployee.Add(emp);
                           else if (!includeInActive && emp.IsActive == true)
                               lstEmployee.Add(emp);
                       }
                   }
               }
               else
               {
                   var tmpList = from employee in objDB_ArjunEntities.Employees.ToList()
                                 where employee.Name == searchKey || employee.Address == searchKey || employee.Email == searchKey
                                 orderby sortingField
                                 select employee;

                   //var query =  from employee in objDB_ArjunEntities.Employees.ToList().Where(objDB_ArjunEntities.Employees. == searchKey || objDB_ArjunEntities.Employees. == searchKey || employee.Email == searchKey).OrderBy("Name asc");

                   foreach (Employee emp in objDB_ArjunEntities.Employees.ToList())
                   {
                       if (includeInActive && (emp.Name.Contains(searchKey) || emp.Address.Contains(searchKey) || emp.Email.Contains(searchKey)))
                           lstEmployee.Add(emp);
                       else if (!includeInActive && emp.IsActive == true && (emp.Name.Contains(searchKey) || emp.Address.Contains(searchKey)))
                           lstEmployee.Add(emp);
                   }
               }
               return lstEmployee;
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }




But the problem is that the sorting is not working properly. The sorting address and sortdirection is correct but the sorting is not working..


Can anyone please help me
Posted
Updated 31-Mar-14 21:38pm
v2

1 solution


You do not have to perform an ascending or descending sort. Just perform an ascending sort and access the resulting list from one end or the other.



By adding .ToList ( ) to the end of your Linq statements, you do not need to add it later on. For example,


C#
temporary =
    ( from employee in objDB_ArjunEntities.
                           Employees.ToList ( )
      orderby sortingField
      select employee ).ToList ( );


In else if of your code:


C#
if (includeInActive)
    lstEmployee.Add(emp);
else if (!includeInActive && emp.IsActive == true)
    lstEmployee.Add(emp);


you do not have to test !includeInActive - we know it's false. Also, ALWAYS place braces around the if statement bodies; because emp.IsActive is a boolean, you only have to test its values. Revised code:


C#
if ( includeInActive )
    {
    lstEmployee.Add ( emp );
    }
else if ( emp.IsActive )
    {
    lstEmployee.Add ( emp );
    }


In the case where a search key is provided, the sort is always ascending. Shouldn't sort order follow the invoker's preference?



Following the statement


C#
var tmpList = from employee in objDB_ArjunEntities.
                                   Employees.ToList()
              where ( employee.Name == searchKey ||
                      employee.Address == searchKey || e
                      mployee.Email == searchKey )
              orderby sortingField
              select employee;


you do not have to retest the same conditions like you do in


C#
foreach ( Employee emp in objDB_ArjunEntities.Employees.ToList ( ) )
    {
    if ( includeInActive &&
         ( emp.Name.Contains ( searchKey ) ||
           emp.Address.Contains ( searchKey ) ||
           emp.Email.Contains ( searchKey ) ) )
        {
        lstEmployee.Add(emp);
        }
    else if ( !includeInActive &&
              emp.IsActive == true &&
              ( emp.Name.Contains ( searchKey ) ||
                emp.Address.Contains ( searchKey ) ) )
        {
        lstEmployee.Add(emp);
        }
    }


Again, all that you need is


C#
if ( includeInActive )
    {
    lstEmployee.Add ( emp );
    }
else if ( emp.IsActive )
    {
    lstEmployee.Add ( emp );
    }


Note that you are not testing against your sorted list (tmpList) but rather against the contents of objDB_ArjunEntities.Employees.ToList ( ). Was that intended?

 
Share this answer
 
Comments
Arjun Menon U.K 3-Apr-14 2:26am    
Hi gggustafson,

Thanks a lot for the detail reply. I have removed some of the conditions you specified and i apologise for putting the old code. Then i have one doubt regarding the sorting case you specified.


You told me not to sort desc, rather always sort in ascending and reverse the list. Out of curiosity , the above code won;t work?


This is the code i have written
var tmpList = from employee in objDB_ArjunEntities.Employees.ToList()
orderby sortingField descending
select employee;

foreach (Employee emp in tmpList.ToList())
{
if (includeInActive)
{
lstEmployee.Add(emp);
}
else if (emp.IsActive)
{
lstEmployee.Add(emp);
}
}
gggustafson 3-Apr-14 9:45am    
Just below your original code is an "Improve Question" button. Click it and put your revised code in place of the original. Then reply to this comment. I'll be notified by your reply.

That way we will be talking about the same thing.
Arjun Menon U.K 3-Apr-14 2:54am    
I think the reason is that the sortfield is not checked for every entity's field in the list
gggustafson 4-Apr-14 14:51pm    
Please finish your statement.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900