Detecting sequences of items with same attribute
-
The subject mostly says it already: I would like to find sequences of items that share an equal attribute. e.g., assume you have some simple object like this:
class myObject {
public int position;
public boolean valid;
}Furthermore assume I'd like to have several instances with unique positions, sometimes valid and sometimes invalid. Can I detect sequences (regarding the order of some attribute such as position) that are valid only? (without having invalid items in between) So if I'd have
(1, true), (2, true), (3, true), (4, true), (5, false), (6, true)
there should be returned(1,2,3),(2,3,4)
when searching for sequences of 3. All I have found is about sequences within the items and so on. There seems to be no way to compare an item with it's neighbouring elements. Or can I use the ElementAt somehow within some select statement..!? Cheers, Roland -
The subject mostly says it already: I would like to find sequences of items that share an equal attribute. e.g., assume you have some simple object like this:
class myObject {
public int position;
public boolean valid;
}Furthermore assume I'd like to have several instances with unique positions, sometimes valid and sometimes invalid. Can I detect sequences (regarding the order of some attribute such as position) that are valid only? (without having invalid items in between) So if I'd have
(1, true), (2, true), (3, true), (4, true), (5, false), (6, true)
there should be returned(1,2,3),(2,3,4)
when searching for sequences of 3. All I have found is about sequences within the items and so on. There seems to be no way to compare an item with it's neighbouring elements. Or can I use the ElementAt somehow within some select statement..!? Cheers, RolandDon Rolando wrote:
everal instances
So you have a list ? I just wrote up something dumb but I am sure you can do it in a more cleaner and scalable way,
List data = new List{
new myObject{position = 1, valid = true},
new myObject{position = 2, valid = true},
new myObject{position = 3, valid = true},
new myObject{position = 4, valid = true},
new myObject{position = 5, valid = false},
new myObject{position = 6, valid = true}
};var query = (from d in data where data.Any(d2 => (d2.position == (d.position + 1)) && (d2.valid == true) ) && data.Any(d3 => (d3.position == (d.position + 2)) && (d3.valid == true) ) select new { id1 = d.position, id2 = d2.position + 1, id3 = d.position + 2 } ); foreach (var op in query) { Console.WriteLine( "id1 ={0}, id2={1}, id2={2}", op.id1, op.id2, op.id3 ); }