我有一个对象列表,每个对象都具有唯一的Key和显示名称(Label)。列表需要保持按每个对象的键排序,但不幸的是,键需要是字符串而不是数字,因此这里的“排序”指的是按字母而不是数字排序的键。(虽然键可以是数字字符串--只要按字母顺序排列,它们的实际字符串值就无关紧要)。
这个列表应该是可重新排序的,但是接下来的键需要重新洗牌,以便它们再次按字母顺序排列。
目前,我的实现允许对列表进行重新排序,然后遍历所有对象,按字母顺序重新分配新的键--我觉得这是个坏主意,因为对于一个值的交换是很费劲的。
我的对象如下所示
class Item
{
public string Key { get; set; }
public string Label { get; set; }
public Item(string key, string label)
{
Key = key;
Label = label;
}
public override string ToString() => Key + ", " + Label;
}我添加了一个扩展方法来处理重排序过程。
static class Utils
{
public static List<Item> MoveIndex(this List<Item> myItems, int from, int to)
{
Item temp = myItems[from];
myItems.RemoveAt(from);
myItems.Insert(to, temp);
for (int i = 0; i < myItems.Count; i++)
{
myItems[i].Key = i.ToString("D2");
}
return myItems;
}
}最后,我给出了扩展方法的示例用法。
static void Main(string[] args)
{
List<Item> myItems = new List<Item>()
{
new Item("0", "Zero"),
new Item("1", "One"),
new Item("2", "Two"),
new Item("3", "Three"),
new Item("4", "Four"),
new Item("5", "Five"),
new Item("6", "Six"),
new Item("7", "Seven"),
new Item("8", "Eight"),
new Item("9", "Nine"),
new Item("10", "Ten"),
new Item("11", "Eleven"),
new Item("12", "Twelve"),
};
myItems.MoveIndex(3, 5);
Console.ReadKey();
}当代码当前处于位置时,在Console.ReadKey()上放置一个断点会显示标签不是按原来的顺序排列,而是键在原来的顺序上--这证明了它目前的工作状态。
在重新排序列表时,是否有更好的方法来管理密钥?也许不需要迭代列表中的所有内容的方式?
有什么更好的字符串我可以用来做钥匙吗?
我知道,这个系统在崩溃前只能容纳100件物品,这是可以的--将进行检查,以确保没有超过这一点。
发布于 2019-04-09 10:14:47
public static List<Item> MoveIndex(this List<Item> myItems, int from, int to)
将代码写入接口,而不是实现:您可以将其重写为
public static IList<Item> MoveIndex(this IList<Item> myItems, int from, int to)如果不是,你几乎可以肯定地把它重写为
public static TList MoveIndex<TList>(this TList myItems, int from, int to)
where TList : IList<Item>for (int i = 0; i < myItems.Count; i++) { myItems[i].Key = i.ToString("D2"); }
首先,我觉得这个绑得太紧了。根据给出的描述,我希望MoveIndex能够处理现有的键,不管它们是什么。
但是,考虑到这里所做的强有力的假设,我想知道是否有一个更好的解决方案,基于完全消除List<Item>。您能否维护一个包含标签的IList<string>,然后用IEnumerable.Select(Func)懒洋洋地生成项目?
发布于 2019-04-09 12:49:53
如果您的需求是在列表中的最大100项,我认为您的实现是可以的。
公共静态List MoveIndex( List myItems,int from,int to) { Item temp = myItems从…;myItems.RemoveAt(from);myItems.Insert(to,temp);for (int i= 0;i< myItems.Count;i++) { myItems我.Key = i.ToString("D2");} return };
一些次要的考虑因素:
如果是from < to,那么通过删除from,您会离开from并向上移动,从而可能会使to索引失效?
对我来说,从这个方法返回列表是违反直觉的,因为您操纵输入列表本身。如果在这里返回一个列表,我希望输入列表不会被修改,返回的列表将是一个保存更改的新实例。
您可以进行一个小的优化,因为只需要将条目从Math.Min(from, to)重新编号为Math.Max(from, to) (都包括在内),因为这些索引之前和之后的所有内容都是不受影响的。
正如Peter所写的,为接口而不是实现编写代码是很好的做法,但是要注意,并不是所有的IList<s>实现都支持RemoveAt(int index)和Insert(int index, T value)。例如,数组没有。因此,在这种特殊情况下,最好还是坚持使用List<Item>
发布于 2019-04-09 14:36:46
你做了很多工作却没有任何收获。如果您真的可以保证列表中不会有超过100个项目,那么为什么不继续创建100个字符串,存储它们,并在您的订购阶段为它们分配项目。
您可以每次只重用相同的字符串集,从不执行任何工作格式,并获得一些效率,因为排序步骤只是通过循环将值从一个数组(按顺序)分配给另一个数组中的对象(按顺序排列):
for (int i = 0; i < myItems.Count; i++)
{
myItems[i].Key = listOf100Strings[i];
}https://codereview.stackexchange.com/questions/217100
复制相似问题