删除列表< T>中的替换元素 [英] Removing alternate elements in a List<T>

查看:141
本文介绍了删除列表< T>中的替换元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不使用占位符列表变量的情况下,在列表< T> 中删除​​备用(奇数索引甚至是索引)元素的最有效方法是什么?



此外,如果你能提到你的每一个答案的成本,这将是非常感激。



我在寻找高效的方法。



$

解决方案如果您为每个移除的项目调用RemoveAt,您将会移动大量数据。最有效的方法是将要保存的项移动到一起,然后删除末尾未使用的项:

  int pos = 0; 
for(int i = 0; i values [pos] = values [i];
}
values.RemoveRange(pos,values.Count - pos);

编辑:

此方法将处理一个百万个int列表女士。使用RemoveAt会花费三分钟...



Edit2:

你可以从pos = 1和i = 2 ),因为第一项不必被复制到自身。这使得代码不太明显。


What is the most efficient way to remove alternate (odd indexed or even indexed) elements in an List<T> without using a place holder list variable?

Also it would be appreciated if you could mention the cost with each of your answer.

I'm looking for an efficient way to do this

Thanks in advance

解决方案

If you call RemoveAt for every item you remove, you will be moving a lot of data. The most efficient is to move the items together that you want to keep, then remove the unused items at the end:

int pos = 0;
for (int i = 0; i < values.Count; i += 2, pos++) {
    values[pos] = values[i];
}
values.RemoveRange(pos, values.Count - pos);

Edit:
This method will process a list of a million ints in 15 ms. Using RemoveAt it will take over three minutes...

Edit2:
You could actually start with pos=1 and i=2 (or 3), as the first item doesn't have to be copied to itself. This makes the code a bit less obvious though.

这篇关于删除列表&lt; T&gt;中的替换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆