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,943 thoughts on “LINQ i Deferred Execution”

  1. I will immediately snatch your rss as I can not find your e-mail subscription hyperlink or newsletter service. Do you’ve any? Please permit me recognise in order that I may just subscribe. Thanks.

  2. Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch since I found it for him smile So let me rephrase that: Thanks for lunch!

  3. I will immediately snatch your rss as I can not find your e-mail subscription hyperlink or newsletter service. Do you’ve any? Please permit me recognise in order that I may just subscribe. Thanks.

  4. 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!

  5. I keep listening to the news update speak about getting free online grant applications so I have been looking around for the best site to get one. Could you advise me please, where could i acquire some?

  6. It is in point of fact a nice and useful piece of info. I am happy that you just shared this helpful information with us. Please keep us informed like this. Thank you for sharing.

  7. My brother suggested I might like this website. He was entirely right. This post actually made my day. You can not imagine simply how much time I had spent for this info! Thanks!

  8. 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.

  9. I simply wanted to say thanks again. I’m not certain the things I would’ve carried out in the absence of these points provided by you regarding such field. It was before a real daunting difficulty in my view, nevertheless considering the very skilled style you treated the issue took me to jump with fulfillment. Extremely grateful for the advice and then expect you comprehend what a great job that you’re putting in training the rest all through your site. Most likely you’ve never met all of us.

  10. 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!

  11. My husband and i felt now lucky that Raymond could round up his research out of the ideas he came across using your web site. It’s not at all simplistic just to choose to be giving freely strategies people today may have been making money from. And we also figure out we’ve got you to be grateful to for that. All of the explanations you made, the easy web site menu, the relationships you help instill – it’s most sensational, and it’s really letting our son in addition to us believe that that situation is pleasurable, and that’s extremely important. Thanks for everything!

  12. Good ¡V I should certainly pronounce, impressed with your website. I had no trouble navigating through all the tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your customer to communicate. Excellent task..

  13. 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..

  14. 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

  15. 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!

  16. I was just looking for this info for a while. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what’s the lack of Google strategy that do not rank this type of informative websites in top of the list. Generally the top web sites are full of garbage.

  17. I as well as my guys were actually digesting the good ideas from your web site then at once I had a terrible feeling I never expressed respect to you for those secrets. The men ended up for that reason warmed to read them and have really been enjoying them. Appreciation for actually being quite kind as well as for making a decision on certain amazing subject matter most people are really wanting to be informed on. My sincere regret for not expressing gratitude to you earlier.

  18. I want to express my appreciation to the writer just for bailing me out of this type of setting. After looking through the world wide web and getting views that were not beneficial, I assumed my entire life was well over. Existing without the presence of solutions to the difficulties you have solved all through your entire write-up is a crucial case, and ones that might have negatively damaged my entire career if I hadn’t come across your blog. Your own personal mastery and kindness in dealing with all areas was tremendous. I don’t know what I would’ve done if I had not discovered such a step like this. I can now look forward to my future. Thanks for your time very much for this reliable and results-oriented help. I will not hesitate to refer your web site to anyone who requires assistance about this issue.

  19. I have to get across my admiration for your generosity supporting persons who really want assistance with the area. Your very own dedication to getting the message all over has been extraordinarily functional and has in every case enabled ladies like me to reach their endeavors. Your new helpful publication signifies a great deal to me and far more to my colleagues. With thanks; from each one of us.

  20. 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.

  21. 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!

  22. Good ¡V I should certainly pronounce, impressed with your website. I had no trouble navigating through all the tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your customer to communicate. Excellent task..

  23. I am not sure where you are getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for excellent information I was looking for this information for my mission.

  24. I have to get across my admiration for your generosity supporting persons who really want assistance with the area. Your very own dedication to getting the message all over has been extraordinarily functional and has in every case enabled ladies like me to reach their endeavors. Your new helpful publication signifies a great deal to me and far more to my colleagues. With thanks; from each one of us.

  25. 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 🙂

Leave a Reply