Sign in to follow this  
Narf the Mouse

[.net] What's a good beginner's resource to learn Linq?

Recommended Posts

Its not really that complex actually, its just a very different syntax than you're used to using in common programming languages (assuming you're using the SQL-like query syntax, rather than the extension method syntax.) You'll also have to get your head around the concept of defered/partial execution, which is one of the keys to using it efficiently. Most common stuff you can achieve through the query syntax, but do be aware that some features are only available through the extension method syntax. Also, where the option is available, use methods defined on the class, rather than linq methods, because they are almost certainly more efficient (eg on List, use the Count property, rather than Linq's Count() method.) This is analogous in C++ to using class methods on STL containers, rather than the general algorithms, when the option is available.

It doesn't go to increadible depth, but "Hooked on Linq" is a small website that has a good amount of beginner-friendly content. Just Google it.


Happy Linqing! Its a very powerful tool for a lot of things, especially when combined with Lambas and expression trees (which are part of the linq package also). At work I've written a parser which takes a bespoke query language, builds an expression tree that represents the query, and then passes that off to linq to get the results. Along the way, due to the use of Linq and the expression tree, type safety gets enforced. Before, when the querry language was translated directly to SQL, injection attacks were a real possibility, but the linq method alleviated a lot of that risk.

Share this post


Link to post
Share on other sites
101 linq examples

Personally I'm not sold on linq. Some of the generic extensions are nice to have, and expression trees are really nice to have. The whole 'common syntax for arbitrary data sources' isn't really there practically, and the syntax is just off from sql enough to be really awkward when doing anything more complex than filtering. I'd personally prefer just Haskell list comprehension syntax for that. And I'll usually just do procedural code in the real world. Easier to read, easier to maintain, easier to debug.

(re: expression trees: I actually just used them in 4.0 to auto-discover properties and do a magical ajaxy databound sortable pagable grid with just a Func<IEnumerable<Dynamic>>. Not that it's practical but damned cool.)

Share this post


Link to post
Share on other sites
Quote:
Original post by Telastyn
101 linq examples

Personally I'm not sold on linq. Some of the generic extensions are nice to have, and expression trees are really nice to have. The whole 'common syntax for arbitrary data sources' isn't really there practically, and the syntax is just off from sql enough to be really awkward when doing anything more complex than filtering. I'd personally prefer just Haskell list comprehension syntax for that. And I'll usually just do procedural code in the real world. Easier to read, easier to maintain, easier to debug.

(re: expression trees: I actually just used them in 4.0 to auto-discover properties and do a magical ajaxy databound sortable pagable grid with just a Func<IEnumerable<Dynamic>>. Not that it's practical but damned cool.)


i guess then you haven't yet noticed how linq works really for everything.

by now my apps have nearly no loops anymore. linq just replaces all sort of filterings, searches, etc. code footprint reduced to about half it's size.

code gets down to stuff like


public void Update(TimeSpan dt)
{
(from o in World.Objects where o.IsActive select o).Each(o => o.Update(dt));
}


(from brain, not 100% sure).

all in all, linq massively streamlines and reduces the amount of code, and linq is "the same everywhere" indeed. i just started with linq-to-xml, which is obviously a bit different, still works quite similar. linq to sql was the start for me, but linq to anything was the wow effect, the reason i fell in love with it.

it looks cryptic at first, but it's not that hard.

and the common extensions are awesome indeed.

one thing that took me a while was to understand the delayed execution. i "got it" right from the start. but sometimes, you don't realize what it really means until some strange bugs appear :)

Share this post


Link to post
Share on other sites
to each it's own. but once you "get" link, you notice how much manual coding is nothing more than query/apply everywhere.

and at this point, you see how much useless time you spent on making a loop with some complex if/else/then blabla in working right, which would have been done with a query much faster.

you talk about performance? i talk about "i optimize for performance WHEN PERFORMANCE IS A PROBLEM".

in short: you said you "don't understand the use of linq yet", and then i show you one, and you say "i can't see this use". which fits your original statement :)

i understand linq and can apply it thus to the situations where it is the most easy and most versatile (at the same time) way to solve an issue. interestingly, this is at VERY MUCH places.

performance? nobody cares about that.

Share this post


Link to post
Share on other sites
Quote:
Original post by davepermen
to each it's own. but once you "get" link, you notice how much manual coding is nothing more than query/apply everywhere.


No, I'm clearly aware how many problems can be simplified to map/reduce or query/apply.

Quote:

and at this point, you see how much useless time you spent on making a loop with some complex if/else/then blabla in working right, which would have been done with a query much faster.


Sorry,

foreach( GameObject entry in World.Objects ){
if( entry.IsActive ){
entry.Update(delta);
}
}


is dead simple. Way more simple than linq syntax. Way easier to read. Way easier to debug. Way easier to refactor/maintain. And I know it's right.

Quote:

you talk about performance? i talk about "i optimize for performance WHEN PERFORMANCE IS A PROBLEM".


That's all well and good, but the performance problems are inherent to linq. The only way to refactor them out is to ditch linq-to-bleh. Switch to ADO or Entity Framework or XPATH or other technologies that provide the same sort of access. The sort of decision that needs to be made at design/technology time.

Quote:

in short: you said you "don't understand the use of linq yet", and then i show you one, and you say "i can't see this use". which fits your original statement :)


I did not say that. I said I was not sold on it. ie: I am not convinced that it is a useful, viable feature; something that will be a 'need to have' for later languages.

I don't think the brevity gained is an advantage usually. The performance and readability isn't too bad for your example, but as soon as you get into any more complex chaining or definitely if you get into any join behavior... you'd be better off using plain old procedural code.

Quote:

performance? nobody cares about that.


Normally I'd agree with you. Performance is the last thing to concern yourself with. But the common places linq is used are the places your program will already be slow: data access, filtering, iteration. And as I said before, it's not something you can just optimize later.

Share this post


Link to post
Share on other sites
mine is a simple one liner, and flexible to be able to handle much more complex tasks in the 5 lines you had to write.

and believe me, once my linq query is 5 lines of filtering and searching, it gets to 20-40 lines of code in your loop, tons of if/else and you have to manually have all that code under control to be always in a valid workflow for all cases.

i don't.

linq reduces the amount of manual iterative processing of data, and thus, too, the amount of chances to make errors by it.

in this trivial example, chance of error is so low that it won't happen.

but once it gets just a bit bigger, it can get hard. and there linq helps in clarity, ease to read (for me much easier to read by now than your piece of code), and lower chance of errors (as the code explains the result, not the way to the result. that is done by the compiler, which, unlike humans, does not make logical errors).

oh, and btw, my code can simply be parallelised at will. can yours? with just one tiny statement?



about performance: well, linq isn't that bad. and you can precompute important in-loop ones if needed to get the speed up (but you knew that i guess).

since moving to linq, and seeing where i can apply it (about anywhere in the codes i write), i reduced the amount of code, am much faster at writing topic-specific fitting solving code, and have much less work at debugging.

so in short, it delivers all that you deny.

you just aren't that fluent at reading it. i am, for me it's natural. more natural by now than loops. (still scared by that thought :))

Share this post


Link to post
Share on other sites
I too think the actual LINQ aspect of the feature (the 'language integrated query') is nasty looking, and I hate reading it -- especially for longer, more complex expressions. It is inelegant.

However you can get the same benefit by using the extension methods that are used to implement the query syntax.

That said, it is absolutely true that terse code isn't better code, and just because you can use LINQ extension methods to refactor a simple loop into a single line doesn't mean that improves the quality of the code; sometimes it does, sometimes it doesn't. Like all tools it has to be applied carefully and in the correct situations.

Share this post


Link to post
Share on other sites
Quote:
Original post by jpetrie
Iand just because you can use LINQ extension methods to refactor a simple loop into a single line doesn't mean that improves the quality of the code; sometimes it does, sometimes it doesn't. Like all tools it has to be applied carefully and in the correct situations.


it reduces the chance to make stupid errors.

Share this post


Link to post
Share on other sites
Quote:
Original post by jpetrie
That's a blanket statement; it doesn't always, especially for more complex queries.


a blanket statement indeed. holds true for me so far, ESPECIALLY for more complex queries.

which is why i stated all the stuff i did: because it works very well for me.

Share this post


Link to post
Share on other sites
Without LINQ I couldn't do stuff like this:

public Board(string input) : this(input.ToCharArray().Select(c => "Xx. -".Contains(c) ? '0' : c).Where(c => char.IsNumber(c)).Select(c => new Cell() { Value = c - '0' }))

or

foreach(var range in ranges) results.Add(ranges.Aggregate(range, (current, item) => (current.Contains(item.Lower) ^ current.Contains(item.Upper)) ? new Range(Math.Min(current.Lower, item.Lower), Math.Max(current.Upper, item.Upper)) : item.Lower < current.Lower && item.Upper > current.Upper ? item : current));

Where would I be without LINQ? [grin]

Share this post


Link to post
Share on other sites
Quote:
Original post by MaulingMonkey
I don't use the language extensions, but I do use the extension methods, personally.


the reason i use the language extensions:

less clutter (less () and less . and less such non-verbal stuff that is implementation detail)
colorization

but the extensions on it's own are great, too, indeed.

Share this post


Link to post
Share on other sites
Quote:
Original post by davepermen
mine is a simple one liner, and flexible to be able to handle much more complex tasks in the 5 lines you had to write.


Forgive me, but I don't see how constraining yourself to the operations provided by linq is more flexible, or able to handle more tasks than procedural code.

Quote:

linq reduces the amount of manual iterative processing of data, and thus, too, the amount of chances to make errors by it.


Maybe for you. For me (and literally, every other programmer I know) the chance of making an error during procedural code is far less than doing the same code in linq, even though the procedural code provides more opportunities for oopsies.

Quote:

but once it gets just a bit bigger, it can get hard. and there linq helps in clarity, ease to read (for me much easier to read by now than your piece of code), and lower chance of errors.


I disagree.

Quote:

oh, and btw, my code can simply be parallelised at will. can yours? with just one tiny statement?



Parallel.ForEach(World.Objects,
entry => {
if( entry.IsActive ){
entry.Update(delta);
}
}
);


Sure, that's mildly more complex. But this ignores all of the parralelization concerns inherent to actually making that switch, all of which are more complex than the actual syntax to implement it.

Quote:

so in short, it delivers all that you deny.

you just aren't that fluent at reading it. i am, for me it's natural. more natural by now than loops. (still scared by that thought :))


Not in my experience. Not in the experience of anyone I know. YMMV and all that.

Share this post


Link to post
Share on other sites
Quote:
Original post by Telastyn
Forgive me, but I don't see how constraining yourself to the operations provided by linq is more flexible, or able to handle more tasks than procedural code.

haven't said that. but reducing the amount of ways to implement the same to the most consistent one (imperative lets you do stuff in many ways) leads to more flexible code.
in the end it all boils down to "change the query", compared to moving around the if statements, redoing the loop with a for loop, or changing the iterations around and all.

but you won't understand that till you understand how linq easens your life anyways.

Quote:

Maybe for you. For me (and literally, every other programmer I know) the chance of making an error during procedural code is far less than doing the same code in linq, even though the procedural code provides more opportunities for oopsies.

you write what you want, and linq handles how it gets there.

with imperative code, you have to manually think what you want, and how you implement it. the amount of additional errors that this introduces happens to beyond your understanding. else you would know how much this statement of you is ridiculous.

a customer comes "i want to get all the phone numbers of our clients".. "oh, but only the gold members, of course".. "oh, and the adress".. "sorted like that".. blablabla

this is all one to one mappable to linq, your job is only to translate.

without linq (or sql or some other query language), have fun rewriting the whole function every time to fit the needs of the customers.

and yes, this more and more fits to gamedev, too.

Quote:

I disagree.

which is why you "don't see the point of linq yet" :)

Quote:

Parallel.ForEach(World.Objects,
entry => {
if( entry.IsActive ){
entry.Update(delta);
}
}
);

and it's still more work.

from entry in World.Objects where entry.IsActive select entry

is a really nice small and EASILY understandable piece of text. what's hard about it? get that list without linq in an as easy to understandable piece of code (and as easy to adapt)

again, talking against a wall. you won't get it.




Quote:

so in short, it delivers all that you deny.

you just aren't that fluent at reading it. i am, for me it's natural. more natural by now than loops. (still scared by that thought :))


Not in my experience. Not in the experience of anyone I know. YMMV and all that.[/quote]

all you said is you don't get linq, and you prove it in every of your posts :)

Share this post


Link to post
Share on other sites
Quote:

all you said is you don't get linq, and you prove it in every of your posts :)

Okay, this response is just inappropriate.

Telastyn has been saying exactly the same kind of thing that you have -- he's simply relating experience with the technology in a subjective manner, as you claim to be (even though you occasionally forget to include those important qualifiers such as "for me," and "in my experience," et cetera).

There is no reason to start insulting him. ASCII smilies don't excuse the behavior. Stop.

Share this post


Link to post
Share on other sites
this was not ment as insult actually. anyways i stop.

linq needs adaption, like other programming constructs (templates, object orientation, parallel stuff, etc) do. some are fast at adapting to linq, seeing it as "the way they think". i'm one of those, and thus, for me, linq was and still is one of the most impressive additions to .net

others a) take longer to adapt, b) never adapt or c) don't even have the need to.

for those, linq is "just another way of the same, hard to learn and such".

imho, Telastyn and the people he know and think the same are in those categories.


but this is not trying to attack them because of this. it's just actually stating the obvious: if you don't "get" linq, then obviously it's not "easy" for that person. he said himself he doesn't see the point in it (which translated roughly to "i don't get it" for me). and thus he doesn't see how it makes live more easy.

and the smile was just sort of a captain obvious smile.


no plan to attack him

Share this post


Link to post
Share on other sites
Quote:

he said himself he doesn't see the point in it (which translated roughly to "i don't get it" for me). and thus he doesn't see how it makes live more easy.

Except that you misunderstood him, as he explained in a subsequent post:
Quote:

I did not say that. I said I was not sold on it. ie: I am not convinced that it is a useful, viable feature; something that will be a 'need to have' for later languages.

It is perfectly possible to understand the technology and still not see a point in it.

The issue of whether or use the LINQ syntax or extension methods is subjective and stylistic insofar as the operations they can provide are equivalent (you cannot do everything with the LINQ syntax you could do with the extension methods). Arguing it is as much use as arguing about brace placement. So we're done with that particular topic.

Share this post


Link to post
Share on other sites
Ah, sorry. I have been looking on MSDN; I've learned some stuff there. And the linked "101 Samples" were excellent; I'm keeping that for future reference. But I'm still not sure what all I can do with Expression Trees.

As for Google, it's inferior to input from individual humans, I've found. Still, I do use it.

Share this post


Link to post
Share on other sites
Expression trees are a fairly advanced topic, and won't see too much use by most people. They're also part of linq, but often considered a separate topic.

Essentially, they're a data representation for functions. You can build and modify the expression tree in memory, and then 'compile' them into a proper delegate that you can then invoke. Lambdas are converted into them (and you can iirc assign a lambda expression to an Expression variable).

They end up being used for runtime code generation, and are much more performant than reflection since (once compiled) expression trees cost the same as any other delegate invocation.

I've used them for dynamically wiring up grids based on reflection info, doing a poor-man's rules engine (storing snippets of a simple domain language in database, then compiling them on the fly), and a few other little reflection bindings. They're way better than the alternatives and pretty easy to use.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this