[英]Filtering a collection based on another collection
I have a List<businessobject>
object collection and a List<string>
object collection. 我有一个List<businessobject>
对象集合和一个List<string>
对象集合。 I want filter my List<businessobject>
so that if a certain property in the business object equals anything the List<string>
it will be filtered out. 我想要过滤List<businessobject>
以便如果业务对象中的某个属性等于List<string>
任何内容,它将被过滤掉。 I can think of writing the code this way, but is there any faster or better way? 我可以想到以这种方式编写代码,但是有没有更快或更更好的方法?
List<businessobject> bo = loadBusinessObjectList();
List<string> stringList = loadStringList();
foreach(businessobject busobj in bo){
if(stringList.contains(busobj.myProperty))
bo.remove(busobj)
}
Your original code will actually not work because you modify the List that you are enumerating. 您的原始代码实际上将不起作用,因为您修改了要枚举的列表。
You can do something like: 您可以执行以下操作:
List<businessobject> bo = loadBusinessObjectList();
List<string> stringList = loadStringList();
var matches = (from b in bo where stringList.Contains(b.SomeProperty) select b);
var bo = bo.Intersect(matches);
If you modify 如果您修改
List<string> stringList
to be 成为
HashSet<string> stringList
performance would be improved, particularly if the number of strings is large because testing for list membership is O(n), while testing for hashset membership approaches O(1). 性能将得到改善,特别是如果字符串数很大,因为对列表成员资格的测试为O(n),而对哈希集成员资格的测试则为O(1)。
Linq is your friend! Linq是您的朋友!
List<businessobject> boList = loadBusinessObjectList();
List<string> stringList = loadStringList();
var badObjects = from bo in boList
where stringList.Contains(bo.myProperty)
select bo;
boList.RemoveRange(badObjects);
比到目前为止发布的其余代码简单得多...
bo.Where(o => !stringList.Contains(o.MyProperty));
List<businessobject> bo = loadBusinessObjectList();
List<string> stringList = loadStringList();
List<businesssobject> bo2 = bo.FindAll(obj => !(stringList.contains(obj.myProperty)));
Not sure if this is faster. 不知道这是否更快。 Instead of removing the objects this one creates a new object with only the ones that match. 它不会删除对象,而是创建一个仅包含匹配对象的新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.