Search code examples
c#linqsortedlist

using linq query to find value that differs from previously found value


Say i have a class that contains these items publicly accessible via properties:

class MyClass
{    
    int switch1; //0 or 1
    int switch2; //0 or 1
    int switch3; //0 or 1
}

This class represents switch states, and each time a switch state changes, i would like to add it to my transition list

I have a large sorted list that contains instances of this class and would like to use a query to capture only the entries in my list where the switch state for any switch changes.

Is this possible using a linq query?


Solution

  • try this:

    Assuming your class looks like:

    public class State
    {
        public int Id { get; set; }
        public int Switch1 { get; set; }
        public int Switch2 { get; set; }
        public int Switch3 { get; set; }
    
        public override bool Equals(object obj)
        {
            var other = obj as State;
    
            if (other != null)
            {
                return Switch1 == other.Switch1 &&
                       Switch2 == other.Switch2 &&
                       Switch3 == other.Switch3;
            }
    
            return false;
        }
    }
    

    I just added an Equals() to compare flags and my Id field is purely to demonstrate which items changed.

    We can then craft a LINQ query like:

        State previous = null;
        var transitions = list.Where(s =>
                                        {
                                            bool result = !s.Equals(previous);
                                            previous = s;
                                            return result;
                                        })
            .ToList();
    

    Not elegant, but it works, if you had this data set:

        var list = new List<State>
                    {
                        new State { Id = 0, Switch1 = 0, Switch2 = 0, Switch3 = 0 },
                        new State { Id = 1, Switch1 = 0, Switch2 = 0, Switch3 = 0 },
                        new State { Id = 2, Switch1 = 1, Switch2 = 0, Switch3 = 0 },
                        new State { Id = 3, Switch1 = 0, Switch2 = 1, Switch3 = 0 },
                        new State { Id = 4, Switch1 = 0, Switch2 = 1, Switch3 = 0 },
                        new State { Id = 5, Switch1 = 0, Switch2 = 1, Switch3 = 0 },
                        new State { Id = 6, Switch1 = 1, Switch2 = 1, Switch3 = 0 },
                        new State { Id = 7, Switch1 = 0, Switch2 = 0, Switch3 = 1 },
                        new State { Id = 8, Switch1 = 0, Switch2 = 0, Switch3 = 1 },
                        new State { Id = 9, Switch1 = 0, Switch2 = 0, Switch3 = 0 },
                    };
    

    And ran the query, the list would contain your state transitions at items: 0, 2, 3, 6, 7, 9