简体   繁体   中英

C# MongoDb SortBy enum

is there any way to SortBy using an enum with the MongoDB driver? I was trying this way but it seems it's not possible to use the same approach as LINQ.

 internal static readonly Dictionary<VehicleAvailabilityStatus, int> enumOrder =
            new Dictionary<VehicleAvailabilityStatus, int>
            {
                {VehicleAvailabilityStatus.Available, 1},
                {VehicleAvailabilityStatus.Reserved, 2},
                {VehicleAvailabilityStatus.NotAvailable, 3},
            };
public async Task<VehicleSearchResult> Search()
        {
            var vehicleCollection = DbContext.GetCollection<Vehicle>();
            var fb = new FilterDefinitionBuilder<Vehicle>();
            var filter = fb.Empty;
            var result = await vehicleCollection.Find(filter).SortBy(x => enumOrder[x.AvailabilityStatus]).ToListAsync();
            return new VehicleSearchResult(result);
        }

The Enum is not ordered as I want, so I need to change the order.

Usually in Mongo Entities you can set your Enum Properties as int with decorations in your POCO .. like:

 [BsonRepresentation(BsonType.Int32)]
public AvailabilityStatus AvailabilityStatus{ get; set; }

So it will be stored in MongoDB as int ... then you can Sort (or OrderBy with Linq) by this field...

Another way could be ... do your Query .. Hit it .. and the Sort in MEMORY

Hope it helps you!

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