Search code examples
c#web-serviceslistviewweb-applicationswindowsformshost

how to sort data from database in listview using c# and entity framework


I'm using Empty Web Application as my host and i have different classes, such as users in it.

I also have a client (Windows Forms app).

Please notice this is Entity framework database!

Ok here's the thing. I want to display sorted data by name in listview.

In my Empty Web app, i have Webservice where i have the code for displaying users.

This is the code, and it works

public Users[] getUsers()
    {
        List<Users> userList = new List<Users>();
        using (var db = new DataBase())
        {
            var query = from x in db.userList
                            select new
                            {
                                ID = x.UserID,
                                name = x.Name,
                                lName = x.LastName,
                                age = x.Age,
                                club = x.Club,
                                price = x.Price
                            };
            foreach (var user in query)
            {
                Users usrLst = new Users();
                usrLst.UserID = ID;
                usrLst.Name = user.name;
                usrLst.LastName = user.lName;
                usrLst.Age = user.age;
                usrLst.Club = user.club;
                usrLst.Price = user.price;
                userList.Add(usrLst);
            }
        }
        return userList.ToArray();

This displays data from my entitiy framework database to listview in my client (windows forms application).

Can you guys please help me fix this, so it gets sorted by name

I would really appreciate any input!


Solution

  • Try this:

       var query = from x in db.userList
                   orderby x.Name
                   select new
                   {
                       ID = x.UserID,
                       name = x.Name,
                       lName = x.LastName,
                       age = x.Age,
                       club = x.Club,
                       price = x.Price
                   };