bill
bill

Reputation: 864

how to get random amount of details from a list or var in c#

I'm reading result from an json file inside the local project.it returns more than 4000 result.I want to get only random number of results (between 500- 1000) from that result.

 var finalResultz = finalResults("All","All","All");//step one

in here it returns more than 4000 results.then I put into a list like this.

List<Results> searchOne = new List<Results>();//step two
foreach(var itms in finalResultz)
{
    searchOne.Add(new Results 
    {
        resultDestination = returnRegionName(itms.areaDestination),
        mainImageurl = itms.testingImageUrl
     });
 }
    
 ViewBag.requested = searchOne;

but I want to get only the results like I said.I want to resize the count in step one or in step two.how can I do that.hope your help.

Upvotes: 2

Views: 68

Answers (2)

David
David

Reputation: 218847

If you want a random count of results, you can just .Take() a random number of the records. First, you'll need a Random:

var random = new Random();

If you want between 500-1000, just get a random value in that range:

var count = random.Next(500, 1001);

Then you can take those records from the collection:

var newList = oldList.Take(count).ToList();

(Of course, you may want to make sure it contains that many records first.)

Note that this will take the first N records from the collection. So in order to take random records from anywhere in the collection, you'd need to shuffle (randomize) the collection before taking the records. There are a number of ways you can do that. One approach which may not be the absolute fastest but is generally "fast enough" for simplicity is to just sort by a GUID. So something like this:

var newList = oldList.OrderBy(x => Guid.NewGuid()).Take(count).ToList();

Or maybe use the randomizer again:

var newList = oldList.OrderBy(x => random.Next()).Take(count).ToList();

Upvotes: 4

Vadim Martynov
Vadim Martynov

Reputation: 8892

You can use Random class and Take() method to extract N elements.

// create new instance of random class
Random rnd = new Random(); 

// get number of elements that will be retrieved from 500 to 1000
var elementsCount = rnd.Next(500, 1000);

// order source collection by random numbers and then take N elements: 
var searchOne = finalResultz.OrderBy(x => rnd.Next()).Take(elementsCount);

Upvotes: 2

Related Questions