Recently I have been working on a project, which involved communication with a lot of external systems. These systems were mainly web services and databases. During the development phase of the project I only had access to a test version of these systems, i.e. dealing with test data. One of these external systems was of a greater interest as it was designed to serve the main data the customer dealed with. It was a traditional SOAP web service (build on ASP.NET). The service contains a bunch of methods to retrieve and update data. Everything seems pretty normal so far. However, a few of these methods that fetch data happened to work very slow. By working slow I mean, that the external server took its time to do the necessary computations. The calls to these methods were sometimes so slow that users had to see a waiting screen for 10 minutes. And this is pretty annoying. And the customer realized it. The first solution was, of course, to ask the customer if it was possible to optimize this service. Unfortunately, the service itself is developed and maintained by another company and it could take some time until a better version was released. We didn’t have this time, so we had to work ourselves on this issue. Continue Reading…
Tag Archives: database
Sort by multiple fields with LINQ
A few days ago I had a small issue concerning sorting. I use LINQ to SQL to get all products from a DB table and sort them by two fields – IsFavorite (boolean) and AddedOn (datetime). Normally, one will write the following LINQ query:
1 2 3 4 |
var query = from p in ctx.Products orderby p.IsFavorite descending, p.AddedOn descending select p; |
However, some people prefer using the C# method-based syntax, which lets you do everything .as the SQL-based one. There is a method, called OrderByDescending() which seems to do exactly what we did in the example above.
1 2 3 4 |
var query = ctx.Products .OrderByDescending(p => p.IsFavorite) .OrderByDescending(p => p.AddedOn); |
Having that, the results I got were sorted only by the AddedOn column. I checked my code 10 times and I couldn’t find what the problem was. FInally, I found my solution – ThenByDescending() method. When you want to sort on multiple columns, the first method you should use is OrderBy (OrderByDescending) and then use ThenBy (ThenByDescending) for all other columns.
1 2 3 4 |
var query = ctx.Products .OrderByDescending(p => p.IsFavorite) .ThenByDescending(p => p.AddedOn); |