If Linq Result Is Empty

前端 未结 2 1004
旧时难觅i
旧时难觅i 2020-12-29 01:31

If I have a linq query that looks like this, how can I check to see if there were no results found by the query?

var LinqResult = 
    from a in Db.Table
            


        
相关标签:
2条回答
  • 2020-12-29 02:16
    if(!LinqResult.Any()) //?
    {
    
    }
    
    0 讨论(0)
  • 2020-12-29 02:32

    You should try to avoid using the Count() method as a way to check whether a sequence is empty or not. Phil Haack has an excellent article on his blog where he discusses this antipattern.

    Count() must actually enumerate all elements of the sequence - which may be expensive if the sequence is based on multiple LINQ operations (or comes from a database).

    You should use the Any() extension method instead - which only attempts to see if there is at least one element in the list, but will not enumerate the entire sequence.

    if( !LinqResult.Any() )
    { 
       // your code
    } 
    

    Personally, I also think that the use of Any() rather than Count() better expresses your intent, and is easier to refactor or change reliably in the future.

    By the way, if what you actually want is the the first (or only) member of the sequence you should use either the First() or Single() operators instead.

    0 讨论(0)
提交回复
热议问题