In LINQ to Entities, how can you order as it should?

I have a request for objects with the "Code" field against them

1.1.1,
1.1.2,
1.1.3,
1.1.4,
...,
1.1.10,
1.1.11

Unfortunately, when I do .OrderBy(x=> x.Code)in the request, it returns in the following order

1.1.1,
1.1.10,
1.1.11,
1.1.2,
1.1.3,
...

How can I make the list of objects sorted by a field of code separated by "." s and how is the integer between each part?

This is customer data, so I can’t just put β€œ0” before 1 number. Also this is any number "." S in this code field.

Let me know if you need more information.

+4
source share
5 answers

If you can make any assumption, how each node can have a maximum of n letters. you can use this code.

.OrderBy(x => String.Concat( x.Code.Split('.')
                                   .Select(ss => ss.PadLeft(3, '0'))) )
+4

. , Version.Parse Linq2Entity, SQL- .

var result = input.AsEnumerable<string>().OrderBy(x => Version.Parse(x.Code));
+5

, , , . Entity Framework, SQL-, , , , , , SQL Entity Framework. SQL Server, SQL :

CREATE FUNCTION dbo.DotSeparatedSort(@input varchar(max))
RETURNS hierarchyid
AS
BEGIN
    return CAST(N'/' + replace(@input, '.', '/') + N'/' AS hierarchyid)
END

hierarchyid, , .

( CAST(N'/' + replace(Code, '.', '/') + N'/' AS hierarchyid) ).

EF- ( EF, ) :

ctx.Entities.OrderBy(c => ctx.DotSeparatedSort(c.Code))

select * from Entities order by dbo.DotSeparatedSort(Code). .

- , , , - .

+1

(OrderBy) (, LINQ to Entities), ORDER BY SQL Expression SQL.

, SQL (, .ToList() ), .

Comparer ( , ..):

public class CodeComparer : IComparer<MyEntity>
{
    public int Compare(MyEntity x, MyEntity y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                return ToComparableString(x.Code).CompareTo(ToComparableString(y.Code));

            }
        }
    }

    private string ToComparableString(string input)
    {
        var split = input.Split(new [] {'.'});
        return string.Join(".", split.Select(x => x.PadLeft(5, '0')));
    }
}

:

var query = (...your Query or data source...).ToList();
var sortedList = query.Sort(new CodeComparer());

"1.15.141" "00001.00015.0141", . ( ., , , 2 5, 99 "node".

0

, :

var result = input.OrderBy(x => int.Parse(x.Code.Split('.')[0]))
                  .ThenBy(x => int.Parse(x.Code.Split('.')[1]))
                  .ThenBy(x => int.Parse(x.Code.Split('.')[2]));
0
source

Source: https://habr.com/ru/post/1693505/


All Articles