[英]Mongo C# driver sort with custom method
The situation: I am using MongoDb C# driver.情况:我正在使用 MongoDb C# 驱动程序。 I have an array string[] values
.我有一个数组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.我已经为我的查询实现了分页,出于某种原因,我需要一个SortDefinition
,它首先对特定集合中具有 id 的元素进行排序,然后才返回其他项目。
Sadly I realized that Mongo driver Sort which is built in only allows sorting by field definition.遗憾的是,我意识到内置的 Mongo 驱动程序 Sort 仅允许按字段定义进行排序。
Try IComparable:尝试 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.