Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change same property in multiple Objects using LINQ?

    private void AllowOtherSelectors(bool value)
    {
        foreach (var c in this.Parent.Controls)
        {
            if (c == this)
                continue;
            if (!(c is RoundGroupedSelector))
                continue;
            var rgs = c as RoundGroupedSelector;

            rgs.AllowMultiple = value;
        }
    }

Although this code works... I feel that it can benefit from using LINQ. This program will be used on a tablet with Atom processors, so i'm just looking for the least resources/cycles used.

like image 874
Robert Snyder Avatar asked May 15 '13 16:05

Robert Snyder


2 Answers

Well, I'd still use a foreach loop, but you can use LINQ for the query part:

foreach (var c in Parent.Controls
                        .OfType<RoundGroupedSelector>()
                        .Where(x => x != this))
{
    c.AllowMultiple = value;
}
like image 158
Jon Skeet Avatar answered Oct 24 '22 21:10

Jon Skeet


I would definitely go for Jon's answer, but just to address your point about "least cycles used" you could possibly make it a bit faster like this:

private void AllowOtherSelectors(bool value)
{
    var saved = this.AllowMultiple;

    foreach (var c in this.Parent.Controls)
    {
        var rgs = c as RoundGroupedSelector;

        if (rgs != null)
            rgs.AllowMultiple = value;
    }

    this.AllowMultiple = saved;
}

I have avoided the if (c == this) test per iteration by making a copy of this.AllowMultiple before the loop and restoring it after. I also removed the redundant use of is.

This would only speed things up if there are quite a few controls and if assigning this.AllowMultiple is very fast and has no side-effects.

I must stress that this kind of micro-optimisation is generally completely pointless, and if you do this kind of thing you must instrument it to see if it really is any faster.

I'm posting this here just for the sake of interest. I'm definitely NOT suggesting that you should actually do this! :)

like image 24
Matthew Watson Avatar answered Oct 24 '22 23:10

Matthew Watson