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

标签 c# linq sortedlist

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

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

这个类表示开关状态,每次开关状态发生变化时,我都想将它添加到我的转换列表中

我有一个包含此类实例的大型排序列表,我想使用查询仅捕获列表中任何开关状态发生变化的条目。

这可以使用 linq 查询吗?

最佳答案

试试这个:

假设你的类(class)是这样的:

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;
    }
}

我刚刚添加了一个 Equals() 来比较标志,而我的 Id 字段纯粹是为了演示哪些项目发生了变化。

然后我们可以像这样设计一个 LINQ 查询:

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

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

    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 },
                };

然后运行查询,列表将包含您在以下项目的状态转换:0、2、3、6、7、9

关于c# - 使用 linq 查询查找与先前找到的值不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7013422/

相关文章:

c# - 如何使用 MongoDB 和 C# 驱动程序查询数组是否为 null 或为空?

c# - `KeyValuePair<string, int>` 的默认值是多少?

c# - 为 json 数据编写 .net 对象

c# - ASP.NET 中的 XML POST 和解析

c# - 如何将 List<Tuple<int, int>> 转换为 Dictionary<int, List<int>>?

c# - SortedList<>、SortedDictionary<> 和 Dictionary<>

c# - 从哈希表中读取 SortedList

c# - 如何处理 WIF 4.5 中的 ActAs token ?

c# - 根据条件合并 List<T> 中的两个或多个 T

java - 从LinkedList的实现继承到SortedLinkedList,访问私有(private)Node