从RSS源中选择2个随机项

时间:2016-04-19 11:36:07

标签: c# list random rss

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

sessionFactory.getCurrentSession();

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

2 个答案:

答案 0 :(得分:1)

您可以使用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);         
}

答案 1 :(得分:0)

我会更好地缓存这些值一段时间而不是每次请求,但如果性能不重要,这里就是一个解决方案

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