我有一种方法可以接受string[]
。它采用这个数组并根据我们拥有的自定义代数公式对其进行排序。这个代数公式是相当复杂的,不能(或不应该)适应除IEnumerable<string>
之外的其他任何东西。快速对对象列表进行排序以匹配包含属性值的数组的顺序
我的任务是为此方法创建一个包装函数,该函数接受IEnumerable<T>
,其中T
实现了一个接口,该接口公开要用于排序的字符串。
基于此,我创建了一个迭代遗传枚举的方法,提取字符串并将结果数组传递给我们的自定义排序函数。这工作,但我结束了一个排序的字符串数组,完全断开原来的IEnumerable <T>
。我如何排序IEnumerable <T>
以匹配从我们的自定义排序函数返回的字符串数组?
例如。
private IEnumerable<T> Sort(IEnumerable<T> objects) where T: ICustomSortable
{
string[] stringsToSort = new string[objects.Count()];
for (int i = 0; i < stringsToSort.length; i++)
stringsToSort[i] = objects.getString();
stringsToSort = customSortFunction(stringsToSort);
//somehow sort the objects so that they are in the same order as stringsToSort?
/*
The result is valid when:
objects[0].getString() == stringsToSort[0]
objects[1].getString() == stringsToSort[1]
objects[2].getString() == stringsToSort[2]
...
objects[n].getString() == stringsToSort[n]
*/
}
编辑:从customSortFunction
检索的字符串可能不是唯一的。这意味着两个字符串相同的objects
都应该存在于结果中。虽然具有相同字符串值的objects
的排序是无关紧要的,但在整体引用结果时应该保持原样。
您是否需要使用customSortFunction()作为一个整体?你能比较两个字符串吗?像'bool customCompare(string1,string2);'? – realharry
不需要我必须使用自定义功能。我必须将它作为一个整体传递给它。 –
好的。我想这是因为性能的原因?因为可以通过调用'customSortFunction()'并在排序前后比较对,轻松实现'customCompare()'函数。 (一对是一个列表,毕竟是一个2元素的列表。) – realharry