I am using LINQ Bridge targetting the .NET 2.0 Framework, and I am getting the following error. Just wanting the first element from a collection, chosen at random. Not concerned about performance in this particular case.
var result = someCollection.OrderBy(g => Guid.NewGuid()).Take(1).FirstOrDefault();
someCollection is a List<string>
. The values in the collection are unique.
Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. x: '', x's type: 'Tuple
2', IComparer: 'System.Array+FunctorComparer
1[LinqBridge.Tuple`2[System.String,System.Int32]]'.
But it seems to work just fine in .NET 4.0. Is there a workaround for this? Unfortunately I'm stuck using .NET 2.0 for this scenario.
EDIT Using the latest version of LINQ Bridge (1.2)
Yet another update
I found this question that has the same issue as you: Why does using Random in Sort causing [Unable to sort IComparer.Compare error]
The problem is that LINQBridge uses
List<>.Sort
internally, which complains when using a "unstable" comparing algorithm, so you unfortunately can't randomize this way.As an alternative, here's some great code to randomize or to choose a random item:
Update
This exception really looks like a LINQBridge bug.
I would recommend updating to the latest version.There's no other apparent reason that you're seeing this issue.Additional Info
You can use a
Random
instead ofGuid
like so:Also,
.Take(1)
is absolutely unnecessary when followed by.FirstOrDefault()