本文发表在 rolia.net 枫下论坛In the original implementation, the adjustindex keep on update in the loop, and the updated value is used to determine if next value match the condition. (please see the adjustedIndex++ within the for loop)
int adjustedIndex = index;
List<int> orderedRemovedItemList = (from each in _removedItemIndexList
orderby each ascending
select each).ToList();
for (int i = 0; i < orderedRemovedItemList.Count; i++)
{
int removedItemPosition = orderedRemovedItemList[i];
if (removedItemPosition <= adjustedIndex)
{
adjustedIndex++;
}
}
However, in your linq query, the count is constant, and it is a fix number. the following unit test will fail with your proposal.
[Test]
public void AdjustIndex1()
{
_list.RemoveAt(0);
Expect(_list[0].ID, EqualTo(999));
Expect(_list[1].ID, EqualTo(998));
Expect(_list[2].ID, EqualTo(997));
}
[Test]
public void AdjustIndex2()
{
_list.RemoveAt(0);
_list.RemoveAt(1);
_list.RemoveAt(3);
_list.RemoveAt(5);
_list.RemoveAt(6);
Expect(_list[0].ID, EqualTo(998));
Expect(_list[1].ID, EqualTo(996));
Expect(_list[2].ID, EqualTo(993));
}
However, i really like the code your proposal. it is simple and easy-to-understand. it is the core of software development.更多精彩文章及讨论,请光临枫下论坛 rolia.net
int adjustedIndex = index;
List<int> orderedRemovedItemList = (from each in _removedItemIndexList
orderby each ascending
select each).ToList();
for (int i = 0; i < orderedRemovedItemList.Count; i++)
{
int removedItemPosition = orderedRemovedItemList[i];
if (removedItemPosition <= adjustedIndex)
{
adjustedIndex++;
}
}
However, in your linq query, the count is constant, and it is a fix number. the following unit test will fail with your proposal.
[Test]
public void AdjustIndex1()
{
_list.RemoveAt(0);
Expect(_list[0].ID, EqualTo(999));
Expect(_list[1].ID, EqualTo(998));
Expect(_list[2].ID, EqualTo(997));
}
[Test]
public void AdjustIndex2()
{
_list.RemoveAt(0);
_list.RemoveAt(1);
_list.RemoveAt(3);
_list.RemoveAt(5);
_list.RemoveAt(6);
Expect(_list[0].ID, EqualTo(998));
Expect(_list[1].ID, EqualTo(996));
Expect(_list[2].ID, EqualTo(993));
}
However, i really like the code your proposal. it is simple and easy-to-understand. it is the core of software development.更多精彩文章及讨论,请光临枫下论坛 rolia.net