简体   繁体   English

使用LINQ在绑定列表中选择与条件匹配的对象?

[英]Select objects in binding list that match criteria using LINQ?

I have a BindingList that contains 100,000 objects. 我有一个包含100,000个对象的BindingList。 Each object contains a bool property that indicates whether the object has been modified or not. 每个对象都包含一个bool属性,该属性指示对象是否已被修改。 I basically want to loop through the objects and when I find one with that bool property set to true, I want to set it to false. 我基本上想遍历对象,当我找到一个将bool属性设置为true的对象时,我想将其设置为false。 Something similar to this: 类似于以下内容:

foreach (myObject obj in bindingListOfMyObjects)
{
    if (obj.Modified)
    {
        obj.Modified = false;
    }
}

Is it possible to do this using LINQ? 是否可以使用LINQ做到这一点? And would that be any faster than the code above? 那会比上面的代码快吗?

No. There's no way of doing this in LINQ. 不。在LINQ中无法做到这一点。 For this to work, you need to modify the elements directly in the BindingList . 为此,您需要直接在BindingList修改元素。 LINQ would simply return a new IEnumerable . LINQ只会返回一个新的IEnumerable

You could use Enumerable.Where to filter the collections, and them modify them in your loop: 您可以使用Enumerable.Where过滤集合,然后在循环中对其进行修改:

foreach (myObject obj in bindingListOfMyObjects.Where(o => o.Modified))
     obj.Modified = false;

This will not be any faster, though it may be slightly easier to understand the intent. 尽管可能会更容易理解意图,但这不会更快。

Note that you wouldn't, in general, use LINQ to actually make the modifications - LINQ queries, by their nature, should not cause side effect (changing the value). 请注意,通常您不会使用LINQ进行真正的修改-LINQ查询就其性质而言,不会引起副作用(更改值)。 They are intended to be used as queries - so filtering the objects is appropriate, and then setting in a loop. 它们旨在用作查询 -因此过滤对象是适当的,然后进行循环设置。 For details, I recommend reading Eric Lippert's post on ForEach vs foreach . 有关详细信息,我建议阅读Eric Lippert在ForEach vs foreach上的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM