2016-04-19 6 views
0

私は現在2つのアイテムを表示していますが、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);   
    } 

です。

答えて

1

であるあなたは2つの乱数を生成するRandomクラスを使用することができ、それらの2を取りますコレクションからの要素。

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

私はより良い代わりに、それぞれの時間を要求するいくつかの時間のために、この値をキャッシュしますが、パフォーマンスはここに重要でない場合は、1つの解決策

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