Welcome to the navigation

Excepteur fugiat aute tempor irure occaecat officia ut duis ullamco ad incididunt exercitation sed laboris nulla in cillum ut consequat, culpa elit, est sunt nisi. Esse in aute irure in elit, duis sed ad labore incididunt ut cillum non laboris commodo consectetur tempor reprehenderit dolor exercitation ut sint consequat, ex

Yeah, this will be replaced... But please enjoy the search!

Getting the previous and next record from list using linq

Categories Tags

Generic lists, you just gotta love them, especially if using linq! Well to the point. Lets say you got a list with Guid's of which you know one and based on that knowledge want to get either the one before or after.

Guid a = new Guid("709DBFA9-88B3-4518-A32F-C21B6AAE2917");
Guid b = new Guid("B9956FC6-FD9B-4F52-B96E-C1D0C29E1E55");
Guid c = new Guid("BFB9054A-AB18-4349-BCB4-19979D3486BB"); // <-- you know this one, the c guid
Guid d = new Guid("1A8D6CAB-FD42-4517-A0EA-08D3F64DCD69");
Guid e = new Guid("02A8CA8A-5BC8-41BE-8AB8-332EF0B5407B");
List<Guid> guidList = new List<Guid> {a, b, c, d, e};

Solution

Oh wow, now I need to start building indexes pushing and popping yada yada. Well no, a better way to solve this is by using linq. Getting the record after the one you search for

private static Guid GetNext(IEnumerable<Guid> guidList, Guid current)
{
    return guidList.SkipWhile(i => !x.Equals(current)).Skip(1).First();
}

And to get the record before...

private static Guid GetPrevious(IEnumerable<Guid> guidList, Guid current)
{
    return guidList.TakeWhile(i => !x.Equals(current)).Last();
}

Using Generics (you should)

Whilst separated methods can be neat sometimes a lot of time and engineering can be saved using some generics instead, this means you can dynamically change the type of list you want to search for a certain record.

In example

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);
    }
}

Some usage

String example

string f = "first";
string g = "second";
string h = "third";
string i = "fourth";
string j = "fifth";
List<string> stringList = new List<string>{f,g,h,i,j};

var prev = GetPrevious<string>(stringList, j);
var next = GetNext<string>(stringList, j);

Guid example

Guid a = new Guid("709DBFA9-88B3-4518-A32F-C21B6AAE2917");
Guid b = new Guid("B9956FC6-FD9B-4F52-B96E-C1D0C29E1E55");
Guid c = new Guid("BFB9054A-AB18-4349-BCB4-19979D3486BB");
Guid d = new Guid("1A8D6CAB-FD42-4517-A0EA-08D3F64DCD69");
Guid e = new Guid("02A8CA8A-5BC8-41BE-8AB8-332EF0B5407B");
List<Guid> guidList = new List<Guid> {a, b, c, d, e};

var prev = GetPrevious<Guid>(guidList, c);
var next = GetNext<Guid>(guidList, c);