LINQ i Deferred Execution

Nie każdy początkujący programista, który zaczyna swoją przygodę z platformą .NET jest świadomy działania  mechanizmów zawartych w technologi którą poznaję. Dobrym przykładem może być tu tworzenie zapytań za pomocą LINQ i Deferred Execution (opuźnione wywołanie). No ale co to oznacza, a no mniej więcej tyle , że zapytania tworzone za pomocą LINQ nie są automatycznie wykonywane podczas ich tworzenia. Wykonanie zapytania jest odłożone w czasie. Aby to wszystko lepiej zrozumieć  przejdźmy do przykładu:

[csharp]
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var result = from n in numbers where n < 5 select n;
numbers[0] = -5;

foreach (var i in result)
{
Console.Write("{0},", i);
}

[/csharp]

Resultat powyższego kody to ciąg liczb: -5,4,1,3,2,0. Zatem jak widać po utworzeniu zapytania nie zostało ono wykonane. Wywołanie zapytania miało miejsce dopiero podczas użycia pętli foreach i element który zmieniliśmy został uwzględniony w końcowym zbiorze.

Skoro już wiemy, że wykonanie zapytania stworzonego za pomocą LINQ nie jest automatycznie wykonywane to pewnie chcieli byście wiedzieć co zrobić żeby od razu dostać dane które chcemy. Odpowiedź jest dość prosta, wystarczy po utworzeniu zapytania wywołać metodę która zwróci nam końcowy zbiór elementów np. ToList, ToArray.

[csharp]int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var result = (from n in numbers where n < 5 select n).ToList();
numbers[0] = -5;

foreach (var i in result)
{
Console.Write("{0},", i);
}
Console.WriteLine();[/csharp]

Wykonanie już takiego kody zwróci nam następujące liczby: 4,1,3,2,0.

Z Deferred Execution w LINQ wiąże się też jedna użyteczna funkcjonalność, a mianowicie możliwość ponownego użycia stworzonego zapytania. Dzięki temu tworzymy zapytanie raz i wykonujemy je dowolną ilość razy na zmodyfikowanym zbiorze.

[csharp]int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var result = from n in numbers where n <= 8 select n;

Console.WriteLine("Result count: {0}",result.Count());

numbers[0] = 11;
Console.WriteLine("Result count (after data changes): {0}", result.Count());

Console.WriteLine("First run");

foreach (var i in result)
{
Console.Write("{0},", i);
}
Console.WriteLine();

for (int i = 0; i < numbers.Length; ++i)
{
numbers[i] = -numbers[i];
}

Console.WriteLine("Second run (after data changes)");

foreach (var i in result)
{
Console.Write("{0},", i);
}
Console.WriteLine();
[/csharp]
Rezultat wykonania powyższego kody będzie następujący:

Result count: 9
Result count (after data changes): 8
First run
4,1,3,8,6,7,2,0,
Second run (after data changes)
-11,-4,-1,-3,-9,-8,-6,-7,-2,0,

Świadomość istnienia mechanizmów takich jak Deferred Execution w LINQ jest bardzo ważna, gdyż taka wiedza uchroni nas przed błędami, których wykrycie staje się bardzo ciężkie. Tak więc podsumowując warto zagłębiać się w tajniki  technologi aby świadomie używać tego co oferuje nam dana technologia.

Przykładowy program można pobrać klikając na poniższy link:[dm]3[/dm]

1,944 thoughts on “LINQ i Deferred Execution”

  1. Thanks for the sensible critique. Me and my neighbor were just preparing to do some research on this. We got a grab a book from our area library but I think I learned more from this post. I’m very glad to see such great info being shared freely out there.

  2. I have read some just right stuff here. Certainly value bookmarking for revisiting. I surprise how much attempt you place to make this type of excellent informative website.

  3. I truly wanted to post a brief comment to be able to thank you for some of the lovely pointers you are sharing at this site. My incredibly long internet search has at the end of the day been honored with excellent facts and techniques to share with my good friends. I ‘d express that most of us site visitors are really lucky to exist in a wonderful site with so many special people with insightful tips and hints. I feel rather blessed to have come across your site and look forward to so many more entertaining moments reading here. Thanks a lot once more for all the details.

  4. hey there and thank you for your info – I have definitely picked up anything new from right here. I did however expertise a few technical issues using this website, as I experienced to reload the web site lots of times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and could damage your high quality score if ads and marketing with Adwords. Anyway I’m adding this RSS to my email and could look out for a lot more of your respective interesting content. Ensure that you update this again soon..

  5. It is perfect time to make some plans for the future and it’s time to be happy. I have read this post and if I could I want to suggest you few interesting things or tips. Maybe you can write next articles referring to this article. I desire to read even more things about it!

  6. We are a group of volunteers and opening a new scheme in our community. Your website offered us with valuable info to work on. You’ve done a formidable job and our entire community will be thankful to you.

  7. I really appreciate this post. I¡¦ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again

  8. I’m extremely impressed with your writing skills as well as with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it’s rare to see a great blog like this one nowadays..

  9. Great post. I found myself checking constantly this blog and I am inspired!

    Extremely helpful info specifically the closing section 🙂 I care for such information a great deal.
    I used to be seeking this certain information for a while.
    Thanks and good luck.

  10. Undeniably believe that which you said. Your favorite justification appeared to be on the net the easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they just don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people could take a signal. Will probably be back to get more. Thanks

  11. It’s the truth is very difficult in this busy life to listen news on Television,
    so I only use the internet for the purpose, and take the
    most recent news.

  12. You actually ensure it is seem really easy with your presentation but I find this topic to
    be actually something that I feel I might never understand.

    It appears too complex and extremely broad for
    me personally. I’m anticipating for your post, I will try to have the hang from it!

  13. This is really interesting, You’re a very skilled blogger. I have joined your feed and look forward to seeking more of your great post. Also, I’ve shared your site in my social networks!

  14. Thank you for sharing excellent informations. Your web-site is so cool. I’m impressed by the details that you have on this blog. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for more articles. You, my pal, ROCK! I found simply the information I already searched everywhere and simply could not come across. What a great site.

  15. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how can we communicate?

  16. Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

  17. I’ve been surfing online more than 3 hours today, but I never discovered any attention-grabbing article like yours. It¡¦s pretty worth enough for me. In my view, if all web owners and bloggers made good content material as you did, the internet can be much more useful than ever before.

  18. I¡¦ve been exploring for a little for any high-quality articles or weblog posts on this kind of area . Exploring in Yahoo I eventually stumbled upon this site. Studying this information So i¡¦m happy to exhibit that I’ve a very excellent uncanny feeling I discovered just what I needed. I most indisputably will make certain to don¡¦t put out of your mind this web site and give it a glance regularly.

  19. I have been absent for a while, but now I remember why I used to love this web site. Thank you, I will try and check back more often. How frequently you update your web site?

  20. When I initially commented I clicked the -Notify me when new feedback are added- checkbox and now each time a remark is added I get four emails with the identical comment. Is there any manner you may take away me from that service? Thanks!

  21. We are a group of volunteers and opening a new scheme in our community. Your website offered us with valuable info to work on. You’ve done a formidable job and our entire community will be thankful to you.

  22. Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

  23. You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  24. I like the helpful info you provide in your articles. I’ll bookmark your blog and check again here frequently. I am quite sure I’ll learn lots of new stuff right here! Best of luck for the next!

  25. My partner and I absolutely love your blog and find
    nearly all of your post’s to be just what I’m looking for.
    Do you offer guest writers to write content in your case?

    I wouldn’t mind publishing a post or elaborating
    on a number of the subjects you write related to here. Again, awesome weblog!

  26. Hello There. I found your blog using msn. This is a really well written article. I will make sure to bookmark it and come back to read more of your useful information. Thanks for the post. I’ll certainly return.

  27. I like what you guys are up also. Such clever work and reporting! Keep up the superb works guys I¡¦ve incorporated you guys to my blogroll. I think it’ll improve the value of my web site 🙂

  28. Thank you for any other wonderful post. The place else may anybody get that type of information in such an ideal way of writing? I’ve a presentation next week, and I am at the look for such info.

  29. Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Great. I’m also an expert in this topic so I can understand your hard work.

  30. you are actually a good webmaster. The website loading velocity is amazing. It seems that you are doing any distinctive trick. In addition, The contents are masterpiece. you’ve done a excellent process on this subject!

  31. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.

  32. I don’t even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!

  33. I have been absent for a while, but now I remember why I used to love this web site. Thank you, I will try and check back more often. How frequently you update your web site?

Leave a Reply

Your email address will not be published. Required fields are marked *