LINQ
Introduction to LINQ in C#
LINQ (Language Integrated Query) is a feature in C# that allows us to perform queries against data sources, which can be arrays, collections, or any type of databases, using a SQL-like syntax. In this article, we will cover some basic concepts and functionalitites of LINQ and learn how to use it in your C# application
Using LINQ with Collections or Lists
The most common way to use LINQ is with collections. In the following example, we will use LINQ to filter a list of integers values and return only the even numbers, You can modify the program according to your requirements:
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var evenNumbers = from number in numbers where number % 2 == 0 select number; foreach (int number in evenNumbers) { Console.WriteLine(number); }
In this example, we will create a list of integers and use the LINQ syntax to filter out the even numbers using the "where" clause of Linq. We then use the "select" clause to select the filtered numbers from the list and store them in the "evenNumbers" variable separately. Finally, we use a foreach loop to iterate over the "evenNumbers" variable and print them to the console or you can use it in any other way as per your requrirements.
Using LINQ with SQL
LINQ can also be used with SQL databases. In the following example, we will use LINQ to query a SQL Server database:
string connectionString = "Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); var customers = from customer in connection.Customers where customer.City == "New York" select customer; foreach (var customer in customers) { Console.WriteLine(customer.FirstName + " " + customer.LastName); } }
In this example, we create a SqlConnection object with a connection string to our SQL Server database. You can pick the connection string from web config file also. We then use the LINQ syntax for querying the "Customers" table or any table which is available in the database and filter out the customers who live in New York. Finally, we use a foreach loop to iterate over the "customers" and print their first and last names to the console.
Conclusion
LINQ is a powerful feature in C# that allows you to perform queries against data sources using a SQL-like syntax. Whether you're working with collections or databases, Using this we can reduce our large code to smaller queries which are more familiar to understand and thus helps increasing the productivity