在删除一个List&LT替代元素; T> [英] Removing alternate elements in a List<T>

查看:118
本文介绍了在删除一个List&LT替代元素; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

谢谢提前

推荐答案

如果你调用RemoveAt移除为每个项目删除,你会被移动大量的数据。最有效的是移动的物品放在一起,你要保留,然后取出在年底未使用的项目:

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);



编辑:

这种方法将处理一百万整数列表中15毫秒。使用RemoveAt移除将需要三分钟......


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

EDIT2:

你可以真正开始POS = 1,I = 2(或3),作为第一项不必被复制到自身。这使得代码有点不太明显不过。


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.

这篇关于在删除一个List&LT替代元素; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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