PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to select random item from IEnumerable using LINQ

 November 04, 2022     c#, lambda, linq     No comments   

Issue

I'm trying to come up a LINQ SELECT statement in C# to select random items from specific object instead of ordered items. how do i translate below syntax to random select

random = _dbase.OrderBy(x => x.company).Take(1000);

Solution

You cannot select a random item from an IEnumerable because it's a generator that yields values. It has no size so you might be dealing with an infinite IEnumerable which makes the selection of a random item impossible.

A work around would be to create a List<T> (which has a size) from your initial collection and then select a random item.

IEnumerable<object> myCollection = ...;

var myList = myCollection.ToList();

var rng = new Random();
var randomIndex = rng.Next(0, myList.Count);
var randomItem = myList[randomIndex];

But in your case, you would prefer not to fetch all data of your table. Instead you could make the calculation inside the sql request.

Here's a link showing how to do it.

Sneak peek in case it becomes invalid

// DO NOT USE THIS FOR MORE THEN 100 ROWS
var randomRecord = foos.OrderBy( x=> SqlFunctions.Rand() ).FirstOrDefault();

// USE THIS FOR MORE THEN 100 ROWS
var random = Math.Random(foos.Count());

var randomRecord = foos.OrderBy( x=> x.id ).Skip( random ).FirstOrDefault();


Answered By - Hervé
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing