Mongo C#驱动程序使用自定义方法进行排序



情况:我使用的是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;
}
}
}

最新更新