繁体   English   中英

Mongo C# 驱动程序排序与自定义方法

[英]Mongo C# driver sort with custom method

情况:我正在使用 MongoDb C# 驱动程序。 我有一个数组string[] values 这是我想以某种方式工作的代码:

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

我已经为我的查询实现了分页,出于某种原因,我需要一个SortDefinition ,它首先对特定集合中具有 id 的元素进行排序,然后才返回其他项目。

遗憾的是,我意识到内置的 Mongo 驱动程序 Sort 仅允许按字段定义进行排序。

尝试 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;
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM