How to use returned linq variable?

前端 未结 3 817
南笙
南笙 2021-01-18 05:00

I\'ve decided to take a quick look into the LINQ side of things, as opposed to just using a straight up foreach loop, but i\'m having some trouble getting it to work, mainly

3条回答
  •  一向
    一向 (楼主)
    2021-01-18 05:43

    Shane,

    I'm not going to improve on the previous answers. They were both correct. I am going to try and explain a little bit to you, so that you understand it in the future a bit better.

    What happens, when you write a piece of code like:

    var selectedSiteType = from sites in siteTypeList
                                   where sites.SiteTypeID == temp
                                   select sites;
    

    you don't put the answer into the var (selectedSiteType), instead, you are creating an expression tree, that is evaluated ONLY when you actually use it (in a foreach, or by calling one of the methods (like .First(), .ToList(), SingleOrDefault(), etc).

    The default return type of a from statement, is an IEnumerable<>, but if you call the .First() or .SingleOrDefault() (etc), you will dive into that IEnumerable<> and get a specific item.

    I hope this helps you better understand what is going on.

    Lemme know if I can add anything or if I got anything wrong.

    Cheers,

    Max

提交回复
热议问题