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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: