0

I have the method below in a webapi that pulls data. I am building an app which will have a listview with default data coming from this method. I want this data to be changing each time any user starts the app.

How can I generate random data with this method. There are about 4 different categories.

        public IEnumerable<ArticlesDto> Find(string  category)
                {
                    IEnumerable<ArticlesDto> objArticles = null;

                    var context = new ArticlesContext();

                        objArticles = (from j in context.Information
                                       where j.Category == category

                                       select new ArticlesDto()
                                       {
                                           Id = j.Id,
                                           Headlines = j.Headlines,
                                           Url = j.Url,
                                           Category = j.Category,
                                           Summary = j.Summary
                                       });
                        return objArticles;                       
                }

Example: first time I use the app, I see a list of data about 20 rows(default data). Second time I use it, I see a different list of another 20 rows different from the last time I used the app.

Baba
  • 2,059
  • 8
  • 48
  • 81

2 Answers2

1

Why don't you try using AutoFixture. This framework would help you generate random data every time your WebAPI call is made. Here the GITHub link. Please mark as answer if this helps.

https://github.com/AutoFixture

Ritwik Sen
  • 296
  • 1
  • 13
1

Just OrderBy a random number and then take as many as you like:

Random rnd = new Random();
objArticles = context.Information.Where(i=> i.Category == category)
.OrderBy(i=> rnd.Next())
.Select(i=> new ArticlesDto
{
     Id = i.Id,
     Headlines = i.Headlines,
     Url = i.Url,
     Category = i.Category,
     Summary = i.Summary
}).Take(20);
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • Good, but doesn't solve the problem _Second time I use it, I see a different list of another 20 rows different from the last time I used the app._ – Steve Aug 27 '17 at 15:52
  • @Steve you mean the first run you always want to see the default data? – Ashkan Mobayen Khiabani Aug 27 '17 at 15:54
  • [After reading this](https://stackoverflow.com/questions/654906/linq-to-entities-random-order) now I am no more sure that your answer works (see J.Skeet answer) – Steve Aug 27 '17 at 15:57
  • I just tried this now and it does not work. I reduced the amount of data returned to 2 and each time I run this it returns more that 2. This is not working – Baba Aug 30 '17 at 00:06
  • Any other idea on how to do this? – Baba Sep 07 '17 at 20:48