【发布时间】:2018-05-01 21:19:58
【问题描述】:
我有一个接受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);? -
没有。我必须使用自定义功能。我必须将整个数组传递给它。
-
好的。我想那是因为性能原因?因为您可以通过调用
customSortFunction()并比较排序前后的对来轻松实现customCompare()函数。 (一对毕竟是一个列表,一个 2 元素列表。)
标签: c# arrays sorting collections ienumerable