[英]Manually removing items from a collection vs using Enumerable.Except C#
To remove objects from a List of custom objects using Except method requires you to implement a IEqualityComparer on the object. 要使用Except方法从自定义对象列表中删除对象,需要在对象上实现IEqualityComparer。 But is it bad just to remove the objects in a normal foreach loop?
但是,仅在正常的foreach循环中删除对象是否不好?
I understand the concept of the IEqualityComparer and using Except but I couldn't get it to work for some reason so I just removed the items manually. 我了解IEqualityComparer的概念并使用Except,但由于某种原因我无法使其正常工作,因此我只是手动删除了这些项目。 Is this considered bad programming?
这被认为是不好的编程吗?
EDIT: using the manual way id have to override Equals and GetHashcode polluting my view model - I guess that's bad? 编辑:使用手动方式ID必须重写Equals和GetHashcode污染了我的视图模型-我猜这很不好吗?
In general, one should avoid making changes to a collection while enumerating. 通常,应避免在枚举时对集合进行更改。
I'm not entirely sure what your original problem is, or why you need to remove elements in such a way, but you're over-complicating the problem. 我不能完全确定您最初的问题是什么,或者为什么需要以这种方式删除元素,但是问题却过于复杂了。 If I understand it right, and you are in fact using a
List<T>
where T is a custom type. 如果我理解正确,实际上您正在使用
List<T>
,其中T是自定义类型。 If this is the case, then simply use a LINQ query to get the values you want from the list. 如果是这种情况,则只需使用LINQ查询即可从列表中获取所需的值。
var newList = oldList.Where(x => x.PropertyName != unwantedValue);
You could use Enumerable.Except
, but it should be noted that Enumerable.Except
returns a set , which is to say, no duplicate values are allowed. 您可以使用
Enumerable.Except
,但应注意Enumerable.Except
返回一个set ,也就是说,不允许重复值。
Also, it should be noted that overriding .Equals
and .GetHashCode
does not pollute the viewmodel, as far as I know. 另外,据我所知,覆盖
.Equals
和.GetHashCode
不会污染视图模型。
Sources: 资料来源:
http://msdn.microsoft.com/en-us/library/vstudio/bb336390(v=vs.100).aspx http://msdn.microsoft.com/en-us/library/vstudio/bb336390(v=vs.100).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.