Suppose I have a list of objects called TheListOfMyObjects
. In that list, there's an object with a property that matches a value: MyObject.TheProperty = SomeValue
.
How can I get the previous 3 objects and the next 3 objects from within this list?
Note that if the object that matches SomeValue
is in first position then I'd need the 3 objects in position 2-5 and the 3 objects in the last 3 positions for a total of 6 objects.
Thanks for your suggestions.
Try this:
var theObj = TheListOfMyObjects.First(x => x.TheProperty == someValue);
var index = TheListOfMyObjects.IndexOf(theObj);
//and from there it's obvious.
In case there's a chance the list won't contain such an element, use FirstOrDefault and check for null on theObj.
Sorry for the late answer, I had problems with the computer. You don't have to add another list, you can solve edge cases with something like this if you have at least 7 objects in your list:
MyObject mo = list.FirstOrDefault(x => x.TheProperty.Equals(SomeValue));
if(mo != null)
{
int index = list.IndexOf(mo);
MyObject moMinus3 = list[(index - 3 + list.Count) % list.Count];
MyObject moMinus2 = list[(index - 2 + list.Count) % list.Count];
MyObject moMinus1 = list[(index - 1 + list.Count) % list.Count];
MyObject mo0 = list[index];
MyObject moPlus1 = list[(index + 1 + list.Count) % list.Count];
MyObject moPlus2 = list[(index + 2 + list.Count) % list.Count];
MyObject moPlus3 = list[(index + 3 + list.Count) % list.Count];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.