find a location for property in a new city

Tuesday, 27 March 2012

Reuse Select function in Linq

You can reuse Linq Select functions by defining a delegate Func field that can be used in multiple Linq queries.

I had a few Linq to Objects queries that were querying the same collection but had different Where clauses that were nested between various if statements. The similarity between all of these statements was the Select function. This was quite long itself and it was annoying seeing such repetition. DRY!

So I tried to create a Func parameter that I could just pass into my Select statement which previously, for example could look like this:

ReturningPerson person;
if (iFeelLikeIt)
{
    person = people.Where(person => person.IsNameFunny)
                .Select(person =>
                    new ReturningPerson
                    {
                        DateOfBirth = input.DateBorn,
                        Name = string.Format("{0} {1}",
                            input.FirstName, input.LastName),
                        AwesomenessLevel = input.KnowsLinq ? "High" : "Must try harder",
                        CanFlyJet = false
                    })
                .FirstOrDefault();
}
else
{
    person = people.Where(person => person.Toes == 10)
                .Select(person =>
                    new ReturningPerson
                    {
                        DateOfBirth = input.DateBorn,
                        Name = string.Format("{0} {1}",
                            input.FirstName, input.LastName),
                        AwesomenessLevel = input.KnowsLinq ? "High" : "Must try harder",
                        CanFlyJet = false
                    })
                .FirstOrDefault();
}

This could be modified to work like this:

Expression<Func<InputPerson, ReturningPerson>> selector = (input) =>
    new ReturningPerson
    {
        DateOfBirth = input.DateBorn,
        Name = string.Format("{0} {1}",
            input.FirstName, input.LastName),
        AwesomenessLevel = input.KnowsLinq ? "High" : "Must try harder",
        CanFlyJet = false
    };
ReturningPerson person;
if (iFeelLikeIt)
{
    person = people.Where(person => person.IsNameFunny)
                .Select(selector)
                .FirstOrDefault();
}
else
{
    person = people.Where(person => person.Toes == 10)
                .Select(selector)
                .FirstOrDefault();
}

Follow britishdev on Twitter

46 comments:

  1. Thank you very much for sharing this information with us!
    professional essay writers

    ReplyDelete
  2. Great blog! It is very useful information! It is really nice.

    ReplyDelete
  3. The academic burden is increasingly gettig heavier among many students, especially those who are also working, as people are being exposed to many issues concerning their areas of study. For instance, a student who is pursing a degree in civil engineering will be required to have adequate knowledge on various issues in the environment!Ok, it is cool paper writing services save your time!

    ReplyDelete
  4. Nice article,short and informative as I like))If you someday looking for essay advanced-writer.com please welcome to my website.

    ReplyDelete
  5. Thanks for this post.Academic paper writing requires in-depth research and analytical skills and exceptional writing service that combines all of these ingredients.I recommend you this www.essays-shark.net one

    ReplyDelete
  6. Interesting site! So much feedback, it's nice to see! I think many will agree with me that now there are many different sites! I would to recommend http://www.essay-mania.com - it's a good project, where everyone can find what he needs!

    ReplyDelete
  7. Oh, no. These tables and charts are too complicated for me. That is why I always order papers in Maths at Custom-Essays-Online.com.

    ReplyDelete
  8. For me it looks like some curse.. I didn't understand even a word(( but I like your blog's design) very cute. I have mine too, but it is more cheerful and sweet. I like to post recipes and vintage photos. Sometimes I order articles for my blog on http://papers-writings.com

    ReplyDelete
  9. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. . Assignment Help

    ReplyDelete
  10. Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting.
    Assignment Help

    ReplyDelete
  11. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. . buy sunglasses

    ReplyDelete
  12. This is wonderful blog and amazing thanks for sharing. Buy assignment uk

    ReplyDelete
  13. I find the information very helpful for all students. You do nice job. Keep on writing and use this reliable source http://academic-writings.com if you need high-quality and original academic writings from degree-holding writers.

    ReplyDelete
  14. This blog is really informative among all thanks a lot for sharing. Economics Assignment Help

    ReplyDelete
  15. Overcoming the Shutdown Crisis: Helping Dysfunctional Politicians With Family Psychology paper writing awesome site

    ReplyDelete
  16. If you have difficulties with your essay, i think best solution for you in this situation visit this site http://essay-professors.com and order your assignments here!

    ReplyDelete
  17. Try our best academic research writing service http://www.essay-experts.org/

    ReplyDelete
  18. AmazingEmulator is the software which is used to run the Android apps on Windows OS. Mobdro Download system employing ARC Welder or Bluestacks so you can stream no cost videos immediately from your computer system. nice.

    ReplyDelete
  19. Wonderful blog with informative contents that provides many information. Here i am introducing Dubai Assignment Help that i found in suffering.

    ReplyDelete
  20. Thanks for sharing such a pleasant opinion, piece of writing is nice, thats why i have read it entirely. assignment helper

    ReplyDelete
  21. Without the shabby and overpowering stench of numerous economically accessible air freshener items, reed diffusers have turned into an inexorably prominent approach to tenderly aroma and refresh indoor air. Marketing Assignment help |

    ReplyDelete
  22. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well need a photographer| content writers

    ReplyDelete
  23. The assignment writers at Students Assignment Help are talented and most devoted. They are well-versed with their work and their areas of knowledge.
    Assignment Help Services

    ReplyDelete
  24. Students Assignment Help is most famous marketing assignment help pair provider around the man. Students hump unseeing faith on our writing skilled. Avail assignment authorship provide at fair soprano?

    ReplyDelete
  25. This blog has provided the helpful data to us continue the good work. I definitely enjoying every little bit of it. It is a great website and nice share. assigment

    ReplyDelete
  26. After read such information i realized your dedication to write this information and i have read your another information that was also good and i wish to get some more interesting things like i read previously about cache cleaner app which helps you to speed up your android device performance even increase storage space.

    ReplyDelete
  27. I am very happy to read this. This is the kind of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best posting. Cost Accounting Assignment Help

    ReplyDelete
  28. The information you provided a very clear and useful for me, thank you. You can visit Highlight Story for reading articles & stories of your choice.

    ReplyDelete
  29. Thanks for sharing this information. I have shared this link with others keep posting such information. to provide best in class law assignment help online at very affordable prices.
    Article Assignment Help
    Essay Assignment Helper
    Essay writing
    Essay writing service
    Dissertation help
    Thesis writing help
    Write My Essay
    Do My Essay
    Hire Cheap Essay Writer
    College Essay Help

    ReplyDelete
  30. I loved the article, keep updating interesting articles. I will be a regular reader I am offering assignment help to students over the globe at a low price.
    Essay writing
    Essay Writer
    seo writing service
    Essay writing service
    Essay writing help
    Write My Essay
    hire seo writer
    hire writer
    Write my essay cheap
    hire article writer

    ReplyDelete
  31. I found this one pretty fascinating and it should go into my collection. Very good work! I am Impressed. We appreciate that please keep going to write more content. We are the assignment helper, we provide services all over the globe. We are best in these:- services
    Digital Markrting Blog
    SEO Blog
    Social Media Blog
    Email Marketeting Blog
    Online marketing Blog

    ReplyDelete
  32. Thanks for sharing this information. I have shared this link with others keep posting such information. to provide best in class law assignment help online at very affordable prices.
    Digital Markrting Blog
    SEO Blog
    Social Media Blog
    Email Marketeting Blog
    Online marketing Blog

    ReplyDelete
  33. I loved the article, keep updating interesting articles.and we serve best food according to our customers' reviews we have a specious hall for marriages & special arrangement for kitty parties and other parties. You can visit us at any time we would love to serve with all our heart!
    verdant marriage palace
    verdant Resort
    marriage palace in Pehowa
    Wedding Venue in Pehowa
    Banquet Hall in Pehowa
    Resort in Pehowa
    Best Resorts near Pehowa
    Best marriage palace in Pehowa
    Best Family Restaurant in Pehowa
    Best Veg Restaurant in Pehowa
    Best Non-Veg Restaurant in Pehowa
    Chwalas 2

    ReplyDelete
  34. Motifz Designer Lawn. 1, 2 & 3 Piece Unstitched Premium Embroidered Lawn 2019, Premium Lawn, Lawn 2019, Best lawn collection, Motifz, Best Lawn in Pakistan, Shipping worldwide. Stitching option available.

    ReplyDelete
  35. hope this piece of information might be useful for all those who are interested in beauty products and all. I think almost all women will like your article. webstagram

    ReplyDelete