How to use returned linq variable?

前端 未结 3 815
南笙
南笙 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:42

    If your return type is a single:

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

    If a list (potentially more than one item):

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

    It's the SingleOrDefault / ToList that you're missing from your query.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-18 05:46

    Use First / FirstOrDefault / Single / SingleOrDefault to get an item of the particular type from the collection.

       var value = selectedSiteType.First(); 
       // returns the first item of the collection
    
       var value = selectedSiteType.FirstOrDefault(); 
       // returns the first item of the collection or null if none exists
    
       var value = selectedSiteType.Single(); 
       // returns the only one item of the collection, exception is thrown if more then one exists
    
       var value = selectedSiteType.SingleOrDefault(); 
       // returns the only item from the collection or null, if none exists. If the collection contains more than one item, an exception is thrown. 
    
    0 讨论(0)
提交回复
热议问题