Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom OrderByDescending() for an IQueryable<T>

Here are some examples of the values I'd like to sort from high to low.

8,929 viewers
18,213 viewers
2,223 viewers
41,231 viewers

And here is an example of the query I'm using:

streams = streamRepository.FindAll()
                          .OrderByDescending(s => s.ViewCount)
                          .Take(4);

This isn't working correctly as I imagine it's taking the parameter as a string, not an int but that's not surprising.

How do you suggest I create this "ordering" using clean C# / Linq code?

Ideally, using the data examples above, the resulting ordered set would be:

41,231 viewers
18,213 viewers
8,929 viewers
2,223 viewers
like image 365
Only Bolivian Here Avatar asked Nov 04 '22 01:11

Only Bolivian Here


2 Answers

Maybe not the neatest solution. But maybe something like this:

streamRepository.FindAll()
        .OrderByDescending(t => t =>Convert.ToDouble(
                 t.ViewCount.Substring(0,t.ViewCount.IndexOf(' '))))

The sql generated. Do not get that horrible and it works in linqpad:

-- Region Parameters
DECLARE @p0 Int = 0
DECLARE @p1 NChar(1) = ' '
-- EndRegion
SELECT [t0].[SomeText]
FROM [Table1] AS [t0]
ORDER BY CONVERT(Float,SUBSTRING([t0].[SomeText], @p0 + 1, 
    (CASE 
        WHEN (DATALENGTH(@p1) / 2) = 0 THEN 0
        ELSE CHARINDEX(@p1, [t0].[SomeText]) - 1
     END))) DESC

Because linq can translate substring and indexof to sql functions. But this is also really specific to the format. Like in the comment to your question I would also suggest you splitting the column into to column.

like image 61
Arion Avatar answered Nov 09 '22 05:11

Arion


If the format is always the same, I'd give this a shot:

streams = streamRepository.FindAll()
    .AsEnumerable()
    .OrderByDescending(s => 
        int.Parse(s.ViewCount.Substring(0, s.ViewCount.IndexOf(' ') - 1))
    .Take(4);
like image 42
Justin Niessner Avatar answered Nov 09 '22 06:11

Justin Niessner