Reputation: 3060
I've been working on next()
and previous()
functionality to move from record-to-record on a IEnumerable<T>
set of data. The methods I came up with work perfectly and always return the type as I need - except for the first and last record. If I look at the last record, I'd like the LINQ to return the first record and if I look at the first record, the previous record will be the last. Making the movement between records endless.
I currently have these methods, (I've renamed the types for privacy):-
private static Teddy _getNext(string code, IEnumerable<Teddy> teddies)
{
return teddies.SkipWhile(i => !i.Code.Equals(code.ToUpper())).Skip(1).FirstOrDefault();
}
private static Teddy _getPrevious(string code, IEnumerable<Teddy> teddies)
{
return teddies.TakeWhile(i => !i.Code.Equals(code.ToUpper())).LastOrDefault();
}
I'd still like the LINQ to return a Teddy
type - otherwise I get into all sort of bother handling null types. Can anyone assist?
Help appreciated.
Upvotes: 0
Views: 204
Reputation: 6112
private static Teddy _getNext(string code, IEnumerable<Teddy> teddies)
{
return teddies.SkipWhile(i => !i.Code.Equals(code.ToUpper())).Skip(1).FirstOrDefault()
?? teddies.First();
}
private static Teddy _getPrevious(string code, IEnumerable<Teddy> teddies)
{
return teddies.TakeWhile(i => !i.Code.Equals(code.ToUpper())).LastOrDefault()
?? teddies.Last();
}
You could use this. It will throw an exception if you pass in an empty teddies collection, though. Using FirstOrDefault() instead would avoid the throw, but return null, which you stated you didn't want.
The ??
is the null coalesce operator, and will return the right hand value if the left evaluates to null. MSDN.
Upvotes: 2
Reputation: 726909
I would try this implementation:
private static Teddy _getNext(string code, IEnumerable<Teddy> teddies)
{
return teddies.SkipWhile(i => !i.Code.Equals(code.ToUpper())).Skip(1).FirstOrDefault()
?? teddies.FirstOrDefault();
}
The way this works is that when the Skip(1)
goes past the end of the input, ensuring that FirstOrDefault()
returns null
, the null-coalescing operator ??
takes the first record from teddies
.
The implementation of getPrevious
will be a "mirror image" of this, using LastOrDefault()
instead of FirstOrDefault()
.
Upvotes: 1