简体   繁体   中英

Mongo C# driver sort with custom method

The situation: I am using MongoDb C# driver. I have an array string[] values . This is the code that I want to make work somehow:

var sort = Builders<Something>.Sort.Descending(x => values.Contains(x.Id));

I have implemented paging for my queries and for some reason I need a SortDefinition which sorts elements with id from a specific collection first and only after that returns other items.

Sadly I realized that Mongo driver Sort which is built in only allows sorting by field definition.

Try IComparable:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication192
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] inputs = { "abcdefg", "stuvwxy", "xyz123", "defghij" };

            string[] outputs = inputs.Select(x => new CustomSort(x)).OrderBy(x => x).Select(x => x.id).ToArray();

        }
    }
    public class CustomSort : IComparable<CustomSort>
    {
        static string[] order = { "def", "abc", "xyz" };
        int index = 0;
        public string id = "";

        public CustomSort(string id)
        {
            this.id = id;
            index = order.Select((x, i) => id.StartsWith(id) ? i : -1).Max(x => x);
        }

        public int CompareTo(CustomSort other)
        {
            int results = 0;
            if (index == -1)
            {
                if (other.index == -1)
                {
                    results = id.CompareTo(other.id);  //neither in list order by string sort
                }
                else
                {
                    results = 1;  //this not i list, other is in list, other < this
                }
            }
            else
            {
                if (other.index == -1)
                {
                    results = -1;  //this in list, othe not in list, this < other
                }
                else
                {
                    index.CompareTo(other.index);  //both in list use index
                }
            }
            return results;
        }

    }
}

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