【发布时间】:2011-10-03 09:22:03
【问题描述】:
鉴于下面的测试用例,我该怎么做:
- 根据匹配的
Id的索引对IList<TestObject>进行排序 在IList<int>列表中。 - 不匹配的值被移到列表的末尾并按其原始索引排序。在这种情况下,由于索引列表中不存在 3 和 4,我们希望看到
list[3] == 3和list[4] == 4。 - 虽然我知道这可以通过 linq 实现,但我需要使用 原始 列表而不是创建新列表(由于列表的存储方式)。
- 源列表必须是
IList(我不能使用List<T>)
这是测试:
public class TestObject
{
public int Id { get; set; }
}
[Test]
public void Can_reorder_using_index_list()
{
IList<TestObject> list = new List<TestObject>
{
new TestObject { Id = 1 },
new TestObject { Id = 2 },
new TestObject { Id = 3 },
new TestObject { Id = 4 },
new TestObject { Id = 5 }
};
IList<int> indexList = new[] { 10, 5, 1, 9, 2 };
// TODO sort
Assert.That(list[0].Id, Is.EqualTo(5));
Assert.That(list[1].Id, Is.EqualTo(1));
Assert.That(list[2].Id, Is.EqualTo(2));
Assert.That(list[3].Id, Is.EqualTo(3));
Assert.That(list[4].Id, Is.EqualTo(4));
}
更新:
根据要求,这是我尝试过的,但 1) 它仅适用于 List<T> 和 2) 我不确定这是最有效的方法:
var clone = list.ToList();
list.Sort((x, y) =>
{
var xIndex = indexList.IndexOf(x.Id);
var yIndex = indexList.IndexOf(y.Id);
if (xIndex == -1)
{
xIndex = list.Count + clone.IndexOf(x);
}
if (yIndex == -1)
{
yIndex = list.Count + clone.IndexOf(y);
}
return xIndex.CompareTo(yIndex);
});
更新 2:
感谢@leppie、@jamiec、@mitch wheat - 这是工作代码:
public class TestObjectComparer : Comparer<TestObject>
{
private readonly IList<int> indexList;
private readonly Func<TestObject, int> currentIndexFunc;
private readonly int listCount;
public TestObjectComparer(IList<int> indexList, Func<TestObject, int> currentIndexFunc, int listCount)
{
this.indexList = indexList;
this.currentIndexFunc = currentIndexFunc;
this.listCount = listCount;
}
public override int Compare(TestObject x, TestObject y)
{
var xIndex = indexList.IndexOf(x.Id);
var yIndex = indexList.IndexOf(y.Id);
if (xIndex == -1)
{
xIndex = listCount + currentIndexFunc(x);
}
if (yIndex == -1)
{
yIndex = listCount + currentIndexFunc(y);
}
return xIndex.CompareTo(yIndex);
}
}
[Test]
public void Can_reorder_using_index_list()
{
IList<TestObject> list = new List<TestObject>
{
new TestObject { Id = 1 },
new TestObject { Id = 2 },
new TestObject { Id = 3 },
new TestObject { Id = 4 },
new TestObject { Id = 5 }
};
IList<int> indexList = new[] { 10, 5, 1, 9, 2, 4 };
ArrayList.Adapter((IList)list).Sort(new TestObjectComparer(indexList, x => list.IndexOf(x), list.Count));
Assert.That(list[0].Id, Is.EqualTo(5));
Assert.That(list[1].Id, Is.EqualTo(1));
Assert.That(list[2].Id, Is.EqualTo(2));
Assert.That(list[3].Id, Is.EqualTo(3));
Assert.That(list[4].Id, Is.EqualTo(4));
}
【问题讨论】:
-
@Mitch,我已经更新了我的问题。我让它工作了,但只有
List<T> -
@Ben - 查看我对 IList 的就地排序的答案,以及可能更有效的比较方法......尽管我认为两者都不会特别慢!
标签: c# .net collections