开发者

using a List<Article> that is ordered, I want to get next/previous urls

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

The l开发者_如何转开发ist 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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜