C# 改变词汇表的关键点
假设我有一个词汇表C# 改变词汇表的关键点,c#,loops,dictionary,iterator,C#,Loops,Dictionary,Iterator,假设我有一个词汇表 public Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>(); 键-1,…,n 现在我想删除第五个元素,但要保持正常的计数 有1、2、3、4、5、6、7、8、9。。。。 而不是1,2,4,6,7,8,9 怎么做 您可以定义此实用程序方法: public static IDictionary<int, T> Remove
public Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
键-1,…,n
现在我想删除第五个元素,但要保持正常的计数
有1、2、3、4、5、6、7、8、9。。。。
而不是1,2,4,6,7,8,9
怎么做 您可以定义此实用程序方法:
public static IDictionary<int, T> RemoveItem<T>(IDictionary<int, T> dict, int key)
{
return dict.Where(kv => kv.Key != key)
.ToDictionary(kv => kv.Key > key ? kv.Key - 1 : kv.Key,
kv => kv.Value);
}
请注意,这不会修改原始dictionary对象,而是创建一个新的dictionary对象,其中key-after键下移1,原始项的key-value键被删除
以下版本确实修改了原始词典,并可能提供稍好的性能和内存使用率:
public static void RemoveItem2<T>(IDictionary<int, T> dict, int key)
{
dict.Remove(key);
T item;
while (dict.TryGetValue(++key, out item))
{
dict.Remove(key);
dict[key - 1] = item;
}
}
你不能用一个列表来代替吗?索引将保持正常的数字使用字典在这里不是很好,因为它不阻止任何顺序。你可能应该看看SortedListI我自己通过索引。也许是SortedDictionary?当然可以,但我需要自己传递钥匙
public static void RemoveItem2<T>(IDictionary<int, T> dict, int key)
{
dict.Remove(key);
T item;
while (dict.TryGetValue(++key, out item))
{
dict.Remove(key);
dict[key - 1] = item;
}
}