2016-04-19 42 views
0

我有一個RSS訂閱源,當前正在顯示2個項目,我想要的是每次頁面重新加載時顯示不同的2個項目。我現在擁有的代碼是從RSS訂閱中選擇2個隨機項目

//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個隨機項目。

回答

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

謝謝你 - 工作處理 – KlydeMonroe

+0

太好了,我很高興它幫助你。 –

0

我會更好的緩存這個值了一段時間,而不是每一次請求,但如果性能是不是在這裏關鍵的是一個解決方案

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