Creating a Custom OrderByDescending () for IQueryable <T>

Here are some examples of values ​​that I would like to sort from high to low.

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

And here is a sample request that I use:

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

This does not work correctly, since I assume that it takes the parameter as a string, not an int, but this is not surprising.

How do you suggest me create this “order” using pure C # / Linq code?

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

41,231 viewers
18,213 viewers
8,929 viewers
2,223 viewers
+3
source share
3 answers

If the format is always the same, I would give this snapshot:

streams = streamRepository.FindAll()
    .AsEnumerable()
    .OrderByDescending(s => 
        int.Parse(s.ViewCount.Substring(0, s.ViewCount.IndexOf(' ') - 1))
    .Take(4);
+1
source

This may not be the best solution. But there might be something like this:

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

sql. , 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

linq substring indexof sql. . , .

+1

- ( , , )...

streams = streamRepository.FindAll()
                          .Select(s=> new { Original = s, Count = ParseToInt(s.ViewCount)})
                          .OrderByDescending(a => a.Count)
                          .Take(3);

... ParseToInt - ( '' int, )

,

EDIT: none-Db

In the case of a related Db query, you need to parse the “string” into int using some SQL function that is mapped (and can be mapped to SQL from linq) - but I'm not sure right away what would be the best way to do this. You also need to make a choice so that it delivers all the data to you.
In this case, as a rule, saving some int field in Db will probably be better (instead of a string)

0
source

All Articles