.NET Framework - Random Order of IEnumerable
Asked By shapper
09-Feb-10 08:43 AM
Hello,
How can I create a collection extension that orders its elements in a
random way? Something like:
public static class CollectionExtensions {
private static Random random = new Random();
public static T OrderRandom<T>(this IEnumerable<T> collection) {
T ordered = default(T);
Int32 count = 0;
foreach (T item in collection) {
// Random order elements?
}
return ordered;
} // Random
}
Thank You,
Miguel
LINQ
(1)
RemoveAt
(1)
ToList
(1)
Random
(1)
IEnumerable
(1)
Correct
(1)
IList
(1)
Randomly.RemoveAt
(1)
Peter Duniho replied to shapper

Can you clarify the question? The method you posted does not order the
elements. Rather, it returns a _single_ element, presumably one that
has been picked randomly.
If you really want a new ordering for the original collection, the
question remains: do you want to actually modify the original
collection? Or are you looking to simply have a differently-ordered
enumeration of the original collection?
If you just want the latter, one possible approach might look like this:
Random rnd = new Random();
var result = from r in
(from c in collection
select new { Item = c, Order = rnd.Next() })
orderby r.Order
select r.Item;
That will return a new order each time you enumerate the "result" query.
If you want to reorder it once, you will have to resolve the query with
a call to "ToList()" and work from that.
An alternative approach would be to copy your collection into an array
and then shuffle the array. There have been several discussions in this
newsgroup discussing shuffle techniques. Just use Google Groups to
search the archives to learn more about that.
Shuffling would be somewhat more efficient than using LINQ (O(n) instead
of O(n log n)), but of course the code is somewhat more complicated and
easier to get wrong (it is particularly important, if you want a true
evenly-distributed randomized order, to exclude already-reordered
elements from subsequent iterations of the shuffle loop).
If you want to permanently reorder the original collection, you can use
either of the above techniques, but apply them directly to the original
collection. With LINQ, you will have to copy the values back to the
original collection. With a shuffle, if the original collection is an
IList<T> or similar, you can just reorder in-place.
Pete
shapper replied to Peter Duniho
{
s
I am using an extension as follows:
public static class CollectionExtensions {
private static Random random =3D new Random();
public static IEnumerable<T> OrderRandomly<T>(this IEnumerable<T>
collection) {
// Order items randomly
List<T> randomly =3D new List<T>(collection);
while (randomly.Count > 0) {
Int32 index =3D random.Next(randomly.Count);
yield return randomly[index];
randomly.RemoveAt(index);
}
} // OrderRandomly
}
Not sure if it is a good approach but it is working and I can reuse it.
Peter Duniho replied to shapper
No, it is about the worst possible implementation you could have chosen.
I offered two approaches, one with O(n) complexity and one with O(n
log n). Instead, you have decided upon one with O(n^2) complexity.
What was wrong with the advice I gave you?
Pete
rossum replied to Peter Duniho
Correct. The classic shuffle algorithm is found in Knuth, Algorithm
3.4.2 P.
rossum
shapper replied to Peter Duniho
T>
Hi Pete,
Nothing wrong with your advice ... I am just using it. :-)
Thank You,
Miguel
ozbea replied to Peter Duniho
How is his solution O(n^2) ?
Is the RemoveAT the culprit?
Oz
--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Linq-to-Sql var null question or observation .NET Framework This is more an observation than MyMatchingTables = null, but rather I get zero hits (or .Count = 0). Must be built into Linq-to-Sql. I have been using it for years but this is the first time AField.StartsWith(aString) select X; / / why is var MyMatchingTables never null? Must be built into Linq to Sql to never return null? myMyTableList = MyMatchingTables.ToList(); } catch (Exception ex) { Debug.WriteLine(ex.Message); / / never triggered, even if no match } return myMyTableList That's what is coming out of the query even if you did not use ToList(), an empty List<T> being created. Now if you were using First() or FirstorDefault(), the the point So this could return a var MyMatchingTables = 3D null? But I thought in Linq-to-Sql that is not allowed? So it will throw an exception (in the try a row out of the table encapsulated as an object / entity, as that is what Linq does. What is Language Integrated Query? LINQ is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages
Is Linq to SQL any good? .NET Framework I am a big fan of linq but in my opinion linq to sql is a complete waste of time. Why on earth take something that is difficult to write by creating a translation layer. I see people here struggling to write linq to sql queries. It also creates the problem of being locked into a particular product 1) Entity Framework (1) Visual Studio (1) Silverlight (1) Oracle (1) If we ignore the LINQ to SQL vs LINQ to EF aspect. You should use LINQ to EF not LINQ to SQL. .NET wanted an ORM. Many people including me like ORM's for certain
linq versus BindingSource. .NET Framework Hello, I think that BindingSource is old fashion attitude. I use filter, I need to retrieve the table data). I want to change my code using linq instead. Before I change 100, 000 lines of code, I need to know whether the linq overcome the performance problems, and is linq indeed is the best way that good for convenience and also good for performance? Is else can I use instead of using BindingSource? Also : Can I write into database via linq? (that is must). Thanks :) C# Discussions SQL Server (1) Entity Framework (1) IDbDataParameter (1) IDbDataAdapter you binding datatables or custom collections? What database are you using? Are you interested in Linq to Datasets, Linq to SQL, Linq to Objects, Linq to XML, or Linq to Entities? Why do you want to change
Kein "First"bei LINQ? .NET Framework Hi, mit dim q = from bla in blub bekomme ich ein IEnumerable(Of <Typ> ). Mit dim o = q.First bekomme ich dann das erste Element. o hat dann den Typ <Typ> . Da Extension members wie 'First' wohl vermutlich (auch) f?r LINQ geschaffen wurden, m?sste es doch irgendwie implementiert sein, oder? So in etwa: dim o from bla in blub _ First wobei o dann gleich vom Typ <Typ> und kein IEnumerable mehr ist. Ich k?nnte zwar schreiben "Take 1", aber das Ergebnis bleibt eine Liste bersehen? - - Armin VB.NET - German Discussions TypeConverterAttribute (1) OrderByDescending (1) FirstOrDefault (1) VB.NET (1) LINQ (1) VB (1) Enumerable (1) Compiler (1) Du kannst den From-Ausdruck klammern: Dim o rlich kann ich das in eine Zeile setzen, aber dann ist das First trotzdem kein LINQ-Ausdruck den ich ja suche. Das Beispiel war nat?rlich vereinfacht, um darzustellen, dass ich 06.2010 13:50, schrieb Peter Fleischer: Den Aufruf der First-Methode ohne Anwendung von LINQ habe ich schon im meinem OP drin. Deine Antwort enth?lt deswegen keinen Mehrwert. Darauf 0} = > {1}", firstItem, q.First) wird (laut Reflector, Umbr?che meinerseits) zu: Dim q As IEnumerable(Of String) = New List(Of String)( _ New String() { "abc", "def" }) _ .Select(Of String
LinQ To Sql Provider - - do we have to create our own? .NET Framework AdventureWorksDataContext dataContext = new contact.EmailPromotion = = 1 select contact; I should probably ask this first: - -> > AdventureWorksDataContext is this the LinQ To Sql provider? If no - - then where does AdventureWorksDataContext come from? If yes, do we for like another data source)? I found an article on msdn Walkthrough: Creating an IQueryable LINQ Provider at http: / / msdn.microsoft.com / en-us / library / bb546158.aspx This seemed fairly involved. If this is the way it is done for LinQ To Sql then I am missing the improved value of this over someting like: SqlConnection see is that you would have the ability to debug the Select Statement with the LinQ approach. Am I putting the pieces together correctly here? Rich * ** Sent via Developersdex http: / / www Server (1) Entity Framework (1) Visual Studio (1) SqlDataAdapter (1) SqlConnection (1) ADO.NET (1) LINQ (1) FirstOrDeFault (1) No, if working with SQL Server you would use the classes in System.Data.Linq for the Sql Provider. AdventureWorksDataContext is a class that inherits from DataContext, much in the a typed DataSet is just an autogenerated class which inherits from DataSet. You *can* use linq-to-Sql directly by means of the DataContext class, but then you would need to