Home > database >  How to pick the previous and next record from a datasource using linq when the datasource is ordered
How to pick the previous and next record from a datasource using linq when the datasource is ordered

Time:08-25

I have come across a situation where I need to show the previous and next record of a matching record , suppose I have a data source for products and the products are sorted by name . Now after retrieving the product by id I also want to retrieve the very next and previous product but in alphabetic order . How can I achieve this using LINQ ?

CodePudding user response:

Sort the list in alphabetic order, find the index of your entry and look for the entries with index /-1.

list = list.OrderBy( x => x.name ).ToList();
list.IndexOf( entry );
var a = list[entry-1];
var b = list[entry 1];

CodePudding user response:

more efficient way without sorting the list:

var a = list.Max( x => x.name < entry );
var b = list.Min( x => x.name > entry );

CodePudding user response:

An efficient non-LINQ answer, assuming the sequence is pre-sorted.

public static IEnumerable<T> Beside<T>(
         this IEnumerable<T> source,
         T target,
         IEqualityComparer<T> comparer = default)
{
    comparer ??= EqualityComparer<T>.Default;
    ArgumentNullException.ThrowIfNull(target);

    T previous = default;
    bool found = false;
    foreach(T item in source)
    {
        if (found)
        {
            yield return item;
            break;
        }
        
        if (comparer.Equals(item, target))
        {
            found = true;
            yield return previous;
        }
        else
        {
            previous = item;
        }
    }
}
  • Related