tags:

views:

72

answers:

2

So I have a List collection that I fetch via a API call (which I don't have any control over).

The list is ordered.

public class Article 
{
     int articleID;
     string Url
}

So I have a Url value, using that I want to figure out the next and previous Url's if any.

What's the most elegant way of doing this?

+5  A: 

Since your list is of type Article...

var foundIndex = articles.FindIndex(a => a.Url == "myUrl");
var previousUrl = (foundIndex > 0 ? articles[foundIndex - 1].Url : null);
var  nextUrl = (foundIndex < articles.Count-1 ? articles[foundIndex + 1].Url : null);
JustLoren
+1 nice: I haven't used FindIndex before... learned something new. :) You have some compile errors, but never mind - your answer demonstrates the principle well.
Mark Byers
Good catch ... that's what I get for copy-pasting ;)
JustLoren
if FindIndex returns an int, why would you declare foundIndex as var?
Rich
Because I'm lazy and it's still compilable?
JustLoren
A: 

You can do this also with LINQ, with some ugly skips and takes :)

class Program
{
    static void Main(string[] args)
    {
        List<Article> list = new List<Article>() { 
            new Article() { articleID = 1, Url = "http://localhost/1" }, 
            new Article() { articleID = 2, Url = "http://127.0.0.1/2" },
            new Article() { articleID = 3, Url = "http://localhost/3" }, 
            new Article() { articleID = 4, Url = "http://127.0.0.1/4" }
        };

        var coll = (from e in list select e).Skip((from e in list where e.Url.Equals("http://localhost/3") select list.IndexOf(e)).First() - 1).Take(3);

        Console.WriteLine(coll.First().Url);
        Console.WriteLine(coll.Last().Url);

        Console.ReadKey();
    }
}

public class Article  
{ 
    public int articleID;
    public string Url;
} 
spookycoder