Search code examples
c#entity-framework-coreef-core-3.1

Order results by the length of varchar/nvarchar column value in EF Core


How can I order the results set by the length of column value in EF Core?

One of the entity properties is barcode, which I need to bring entities with shorter barcodes on top of the list while searching the value likeliness not exact match.

In SQL :

Select * 
From dbo.Barcodes 
Where BarcodeValue Like '%221%'
Order By Len(BarcodeValue) Asc

How to do this in EF Core?


Solution

  • dbo.Barcodes.Where(x => x.BarcodeValue.Contains("221")).OrderBy(x=> x.BarcodeValue.Length)