[英]How do I move items from a list to another list in C#?
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? 为了获得最快/最好的代码,还有更好的方法吗?
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);
I suggest: 我建议:
var selected = items.Where(item => item.Something > 10).ToList();
items = items.Except(selected).ToList();
otherList.AddRange(selected);
RemoveAll goes trough each item and enumerates all values of your selected list every time. RemoveAll会遍历每个项目,并且每次都会枚举所选列表的所有值。 This will take longer than it should... 这将花费更长的时间......
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));
That is quite bad performance wise - it actually enumerates a query n times (for n items in items
). 这是非常糟糕的性能 - 它实际上枚举了一次查询n次(对于项目中的n个items
)。 It would be better if you built (for example) a HashSet<T>
of the items to manipulate. 如果构建(例如)要操作的项的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);
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.