Getting the previous and next record from list using linq
Get previous and next record from list using linq.
Method GetNext and GetPrevious
usage
Method GetNext and GetPrevious
private static T GetNext<T>(IEnumerable<T> list, T current) { try { return list.SkipWhile(x => !x.Equals(current)).Skip(1).First(); } catch { return default(T); } } private static T GetPrevious<T>(IEnumerable<T> list, T current) { try { return list.TakeWhile(x => !x.Equals(current)).Last(); } catch { return default(T); } }
usage
List<string> stringList = new List<string>(); stringList.Add("first"); stringList.Add("second"); stringList.Add("third"); stringList.Add("fourth"); stringList.Add("fifth"); // Find next record from the list String nextString = GetNext(stringList, "second"); // Output : third // Find previous record from the list String perString = GetPrevious(stringList, "fifth"); // Output : fourth
Getting the previous and next record from list using linq
Reviewed by Bhaumik Patel
on
11:10 PM
Rating: