如何在 C# 中将项目从列表移动到另一个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1029268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I move items from a list to another list in C#?
提问by Stécy
What is the preferable way for transferring some items (not all) from one list to another.
将某些项目(不是全部)从一个列表转移到另一个列表的首选方法是什么。
What I am doing is the following:
我正在做的是以下内容:
var selected = from item in items
where item.something > 10
select item;
otherList.AddRange(selected);
items.RemoveAll(item => selected.Contains(item));
In the interest of having the fastest/best code there is, is there a better way?
为了拥有最快/最好的代码,有没有更好的方法?
采纳答案by Scott Ivey
I'd try @Mehrdad's answer, and maybe test it against this one too...
我会尝试@Mehrdad的答案,也许也可以针对这个答案进行测试......
var selected = items.Where(item => item.Something > 10).ToList();
selected.ForEach(item => items.Remove(item));
otherList.AddRange(selected);
回答by Mehrdad Afshari
I suggest:
我建议:
var selected = items.Where(item => item.Something > 10).ToList();
items = items.Except(selected).ToList();
otherList.AddRange(selected);
回答by Marc Gravell
That is quite bad performance wise - it actually enumerates a query n times (for n items in items
). It would be better if you built (for example) a HashSet<T>
of the items to manipulate.
这是非常糟糕的性能 - 它实际上枚举了 n 次查询(对于 n 个项目items
)。如果您构建(例如)一个HashSet<T>
要操作的项目会更好。
To give a simple example just with int
values:
举一个简单的例子,只用int
值:
var items = new List<int> { 1, 2, 3, 4, 5, 6 };
var otherList = new List<int>();
var selected = new HashSet<int>(items.Where(
item => item > 3));
otherList.AddRange(selected);
items.RemoveAll(selected.Contains);
回答by Meta-Knight
RemoveAll goes trough each item and enumerates all values of your selected list every time. This will take longer than it should...
RemoveAll 遍历每个项目并每次枚举所选列表的所有值。这将花费比它应该更长的时间......
What I'd do is put the condition directly in the RemoveAll parameter:
我要做的是将条件直接放在 RemoveAll 参数中:
items.RemoveAll(item => item.something > 10);
If you do this and don't change the rest of your code there would be code duplication, which is not good. I'd do the following to avoid it:
如果您这样做并且不更改其余代码,则会出现代码重复,这并不好。我会做以下事情来避免它:
Func<ItemType, bool> selectedCondition = (item => item.something > 10);
otherList.AddRange(items.Where(selectedCondition));
items.RemoveAll(new Predicate<ItemType>(selectedCondition));
回答by Ray
How about a partition:
分区怎么样:
int[] items = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var partition = items.ToLookup(x => x > 5);
var part1 = partition[true];
var part2 = partition[false];