Linq to Entities - SQL “IN” clause

前端 未结 8 1248
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 05:10

In T-SQL you could have a query like:

SELECT * FROM Users WHERE User_Rights IN (\"Admin\", \"User\", \"Limited\")

How would you replicate t

8条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:55

    I will go for Inner Join in this context. If I would have used contains, it would iterate 6 times despite if the fact that there are just one match.

    var desiredNames = new[] { "Pankaj", "Garg" }; 
    
    var people = new[]  
    {  
        new { FirstName="Pankaj", Surname="Garg" },  
        new { FirstName="Marc", Surname="Gravell" },  
        new { FirstName="Jeff", Surname="Atwood" }  
    }; 
    
    var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered  select p.FirstName).ToList(); 
    

    Disadvantages of Contains

    Suppose I have two list objects.

    List 1      List 2
      1           12
      2            7
      3            8
      4           98
      5            9
      6           10
      7            6
    

    Using Contains, it will search for each List 1 item in List 2 that means iteration will happen 49 times !!!

提交回复
热议问题