假设我有一个类,其中包含可通过属性公开访问的这些项目:
class MyClass
{
int switch1; //0 or 1
int switch2; //0 or 1
int switch3; //0 or 1
}
此类表示开关状态,每次开关状态改变时,我想将其添加到我的转换列表
我有一个包含此类实例的大型排序列表,并希望使用查询仅捕获列表中任何开关的开关状态发生变化的条目。
这是否可以使用linq查询?
答案 0 :(得分: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;
}
}
我刚刚添加了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
答案 1 :(得分:1)
我会这样做:
class MyClass
{
int ID; //needs for recognize the message
int switch1; //0 or 1
int switch2; //0 or 1
int switch3; //0 or 1
public int Pattern
{
get { return switch1 + switch2 << 1 + switch3 << 2; }
}
}
然后必须将其声明为包含先前状态消息的字典:
Dictionary<int, int> _prevStates;
每个单元格用于键入ID,并且值为消息的“模式”。 此时,我们假设新的传入消息流是MyClass的列表:
IEnumerable<MyClass> incoming = ...
var changed = from msg in incoming
where _prevStates.ContainsKey(msg.ID) //what to do?
where _prevStates[msg.ID].Pattern != msg.Pattern
select msg;
最后,您必须使用更改的模式更新字典。
干杯