LINQ Confusion
Posted by Tyler | Filed under Projects
I find myself using LINQ a lot in my C# code these days. I use collections all over the place, and there’s no doubt that LINQ makes sorting and slicing collections a lot simpler code-wise.
In my most recent weekend project, I need to randomly sort a list of cards, which are represented by an Action class. After some quick searching, I found some articles that indicated the best way to do this would be to sort the list by random GUID. This makes sense, though I certainly wouldn’t have thought of it on my own.
The examples given all worked, but not with my lists… With the following code, the compiler spits out several errors:
List<Action> cards = new List<Action>(); cards.Add( new OneCattle() ); cards.Sort( a => Guid.NewGuid() ).ToList<Action>(); Error 1 Delegate 'System.Comparison<agricola.Action>' does not take '1' arguments Error 2 Cannot convert lambda expression to type 'System.Collections.Generic.IComparer<agricola.Action>' because it is not a delegate type Error 3 Cannot implicitly convert type 'System.Guid' to 'int' Error 4 Cannot convert lambda expression to delegate type 'System.Comparison<agricola.Action>' because some of the return types in the block are not implicitly convertible to the delegate return type
However, using a more explicit LINQ query without a lambda expression seems to work fine:
var q = from a in cards
orderby Guid.NewGuid()
select a;
List<Action> r = q.ToList<Action>();
Anybody know why this is? I haven’t wrapped my head around lambda expressions and the theory behind LINQ to understand what the root cause is…
2 Responses to “LINQ Confusion”
-
Stitch Says:
April 30th, 2009 at 1:50 pmFirst of all, I believe the second code snippet is not “a more explicit LINQ query”. It is actually the more syntactic-sugar version.
Second of all, you calling .Sort and doing a linq orderby are completely different operators. If we you were to call cards.OrderBy(a => Guid.NewGuid()) then the two would be effectively equivelant.
Thirdly, Sort() does not take a lambda expression. It takes an IComparer amongst other things.
And finally, to go back to the “more explicit linq query” part: here is the “explicit” version of that linq query in the second code snippet:
var q = cards.OrderBy(a => Guid.NewGuid()).Select(a => a);
Cheers
-
Tyler Says:
May 7th, 2009 at 11:32 amThanks! I realize now that I made a stupid mistake… I’m working on a follow-up post to clarify.
Hello, visitor from the Internet. You may have arrived here expecting to see a site built on top of SharePoint, and are no doubt confused by the fact that tylerbutler.com is running on WordPress.
You can subscribe to this site in a variety of different ways. The best and simplest way is via RSS. There are three main RSS feeds: