[英]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.