从RSS源中随机选择2个项目

本文关键字:选择 2个 项目 随机 RSS | 更新日期: 2024-10-19 02:53:47

我有一个RSS提要,我目前正在显示两个项目,我想要的是每次重新加载页面时都会显示不同的两个项目。我目前拥有的代码是

//BBC UK 
string RssFeedUrl = "http://feeds.bbci.co.uk/news/uk/rss.xml?edition=uk";

List<Feeds> feeds = new List<Feeds>();
try
{
    XDocument xDoc = new XDocument();
    xDoc = XDocument.Load(RssFeedUrl);
    var items = (from x in xDoc.Descendants("item").Take(2)
    select new
    {
        title = x.Element("title").Value,
        link = x.Element("link").Value,
        pubDate = x.Element("pubDate").Value,
        description = x.Element("description").Value
    });
    foreach (var i in items)
    {
        Feeds f = new Feeds
        {
            Title = i.title,
            Link = i.link,
            PublishDate = i.pubDate,
            Description = i.description
        };
        feeds.Add(f);         
    }

如何更改为每次重新加载页面时随机选择2个项目。

从RSS源中随机选择2个项目

您可以使用Random类生成两个随机数,并从集合中获取这两个元素。

    int[] randints =  new int[2];
    Random rnd = new Random();
    randints[0] = rnd.Next(0, xDoc.Descendants("item").Count()); // creates first random number

    do 
    {
        randints[1] = rnd.Next(0, xDoc.Descendants("item").Count()); // creates second random number
    }while (randints[1] == randints[0]); // make sure that you don't have duplicates.

var items = xDoc.Descendants("item")
     .Skip(randints[0]-1)
     .Take(1)
     .Concat(xDoc.Descendants("item")
                .Skip(randints[1]-1)
                .Take(1))
     .Select(x=> new
      {
           title = x.Element("title").Value,
           link = x.Element("link").Value,
           pubDate = x.Element("pubDate").Value,
           description = x.Element("description").Value
      });
foreach (var i in items)
{
    Feeds f = new Feeds
    {
        Title = i.title,
        Link = i.link,
        PublishDate = i.pubDate,
        Description = i.description
    };
    feeds.Add(f);         
}

我最好将这些值缓存一段时间,而不是每次都请求,但如果性能不关键,这里有一个解决方案

XDocument xDoc = XDocument.Load(RssFeedUrl);
var rnd = new Random();
var twoRand = xDoc.Descendants("item")
              .OrderBy(e => rnd.Next()).Take(2).Select(...)
              .ToList();