使用linq查询查找与先前找到的值不同的值

Jas*_*son 4 c# linq sortedlist

假设我有一个类,其中包含可通过属性公开访问的这些项:

class MyClass
{    
    int switch1; //0 or 1
    int switch2; //0 or 1
    int switch3; //0 or 1
}
Run Code Online (Sandbox Code Playgroud)

此类表示切换状态,每次切换状态更改时,我都想将其添加到转换列表中

我有一个大的排序列表,其中包含此类的实例,并希望使用查询仅捕获列表中任何开关的开关状态更改的条目.

这可能使用linq查询吗?

Jam*_*are 5

试试这个:

假设你的班级看起来像:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我刚添加了一个Equals()比较标志,我的Id字段纯粹是为了证明哪些项目发生了变化.

然后我们可以创建一个LINQ查询,如:

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

不优雅,但如果你有这个数据集它可以工作:

    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 },
                };
Run Code Online (Sandbox Code Playgroud)

并运行查询,列表将包含项目的状态转换:0,2,3,6,7,9