Replicating the 'IN' operator in LINQ

We often use the 'IN' Operator to specify multiple values in the WHERE clause. What if you have to do something similar in LINQ. Here's a simple example that demonstrates this. The example searches out the desired pincodes in a list of Booth Addresses.

C#


var pinCodes = new[] { 411021, 411029, 411044 };


var Booths = new[] {


    new { BoothName = "Booth1", PinCode = 411011 },


    new { BoothName = "Booth2", PinCode = 411021},


    new { BoothName = "Booth3", PinCode = 411029 },


    new { BoothName = "Booth4", PinCode = 411044 },


    new { BoothName = "Booth5", PinCode = 411056 },


    new { BoothName = "Booth6", PinCode = 411023 },


    new { BoothName = "Booth7", PinCode = 411024 }


};


 


var whereAmI = from booth in Booths


              join pins in pinCodes


              on booth.PinCode equals pins


              select booth;




VB.NET


        Dim pinCodes = New Integer() {411021, 411029, 411044}


        Dim Booths = New Object() _


        {New With {Key .BoothName = "Booth1", Key .PinCode = 411011}, _


        New With {Key .BoothName = "Booth2", Key .PinCode = 411021}, _


        New With {Key .BoothName = "Booth3", Key .PinCode = 411029}, _


        New With {Key .BoothName = "Booth4", Key .PinCode = 411044}, _


        New With {Key .BoothName = "Booth5", Key .PinCode = 411056}, _


        New With {Key .BoothName = "Booth6", Key .PinCode = 411023}, _


        New With {Key .BoothName = "Booth7", Key .PinCode = 411024}}


 


        Dim whereAmI = _


         From booth In Booths _


         Join pins In pinCodes On booth.PinCode Equals pins _


         Select booth




OUTPUT

No comments:

Post a Comment