简体   繁体   中英

Trying to Use Sort Order from LINQ Query to Structure SQL Query

I have a LINQ query that sorts based on the following:

.OrderByDescending (l => l.foo == "ASDF")
.ThenByDescending (l => l.IsValid)
.ThenByDescending (l => l.Category == "X")
.ThenByDescending (l => l.Size)
.ThenByDescending (l => l.Description.Contains("Y")
.Thenby (l => l.ShelfNumber)
.Thenby (l => l.ItemNumber)
.ToList()

I'm sure there's possibly a better way to write that query, but my question is how am I able to write a SQL clause for a view that sorts in that fashion?

The ORDER BY clause, from what I've seen, doesn't allow you to base it off of any values, just columns.

To order based on a value in a SQL-Statement you can use the CASE Statement like this:

SELECT *
FROM [YourTable]
ORDER BY
   (CASE
      WHEN [foo] = 'ASDF' THEN 1
      WHEN NOT ([foo] = 'ASDF') THEN 0
      ELSE NULL
    END) DESC

You could use more complex comparisons using an implementation of IComparer, for example:

My comparator class for an item:

private class MyComparer : IComparer<Tuple<int, int>>
{
    private readonly double extraData;

    public MyComparer(double extraData)
    {
        // TODO: Complete member initialization
        this.extraData = extraData;
    }

    public int Compare(Tuple<int, int> x, Tuple<int, int> y)
    {
        if (extraData < 10)
            return x.Item1 - x.Item1;
        else
            return x.Item2 - x.Item2;
    }
}

And the code:

List<Tuple<int, int>> collection = new List<Tuple<int, int>>();
//Fill the list...
double extraData = 0.5d;
MyComparer comparer = new MyComparer(extraData);
collection.OrderByDescending(x => x, comparer);

The problem is if you want to use anonymous structures created in a previous LINQ you can not do in this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM