skip to Main Content

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 ?

3

Answers


  1. 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];
    
    Login or Signup to reply.
  2. more efficient way without sorting the list:

    var a = list.Where( x => x.name < entry ).Max( x => x.name );
    var b = list.Where( x => x.name > entry ).Min( x => x.name );
    
    Login or Signup to reply.
  3. 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;
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search