How to make the previous and next item in the list <G>
I have a class called Person that contains various properties such as first name, last name, etc.
I have a list containing n instances of Person.
List<Person> lstPerson = new List<Person>(); What I need to do is search for lstPerson for a given person, and, finding this person, then get the previous and next person relative to the position of the person in lstPerson.
Person p = lstPerson.Find(delegate(Person o) { return o.FirstName == "Joe"; }); // Then use an accessor to get the previous and next persons Person prevPerson = p.Previous(); Person nextPerson = p.Next(); Is there a better way to do this than the one I outlined above? What I don't like about this solution is that I had to create the previous and next pointers while I was creating a list of faces.
You can do something like the following:
int personIndex = lstPerson.FindIndex(delegate(Person o) { return o.FirstName == "Joe" }); Person p = lstPerson[personIndex]; // verify that personIndex+1 and personIndex-1 still fall within the list Person prevPerson = lstPerson[personIndex-1]; Person nextPerson = lstPerson[personIndex+1]; Hmm .. why not just use the LinkedList class ? It comes with the following and previous built-in.
You can do this, which skips the items until the next item matches or the whole list goes through:
var list = (new List<Person>() { null }).Concat(lstPerson); var p = list.SkipWhile((x, index) => { var n = list.ElementAtOrDefault(index + 1); return n == null || n.FirstName != name; }).Take(3); Person previous = p.FirstOrDefault(); Person person = p.ElementAtOrDefault(1); Person next = p.ElementAtOrDefault(2); Although this (similar to @marcind answer) may be more clear:
Person person = lstPerson.Find(p => p.FirstName == name); Person previous = null; Person next = null; if (person != null) { int index = lstPerson.IndexOf(person); previous = lstPerson.ElementAtOrDefault(index - 1); next = lstPerson.ElementAtOrDefault(index + 1); }