LINQ(Language Integrated Query)

Server Tombak
4 min readNov 24, 2023

--

Hello, In this article we will be talking about LINQ(Language Integrated Query) which help us a lot when we are dealing with any kind of data.

We are using databases for hold the data and when we want to fiter data we can use LINQ instead of writing complex queries with SQL to get them. And thats why even if we dont know to write sql queries we can filter and return data as we need.

Lets assume that we have an E-commerce website and we are holidng our Customers in our database table and we need to get all customers who did not validate their email addresses.

Lets say that we have 1000 user and 345 of them did not validate their email and we are holding that information in database. To get this 345 person we have to check the all of them and look if the IsEmailValidated bool value is true or false.

instead of writing an SQL query we can make this opertaion with LINQ method:

customers.Where(c =>c.IsEmailValidated == false).ToList();

in this example we are assuming that customers is a data query and with Where method we are checking all the Customers’ IsEmailValidated value if its false we are selecting and with ToList method we are putting it to a list. This data store can be coming from an XML, Array, List or Database it does not matter where the data is coming from because as you can understand from the name its Language Integrated Query. And for use LINQ methods we dont need to add any new package from nuget packages its coming from System.Linq library which is already available when you create the project.

I have created a github repo for the below examples you can access source code from here

Lets make some HTTP GET requests and use LINQ to filter and get data from a database.

    public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
[ForeignKey("Category")]
public Guid CategoryId { get; set; }
}
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; } // Every category can have more than one Product
}

We have two classes: Product and Category. Each Product instance will holding a categoryId to make connection with Category Table.

I have completed the database connection and added fake 150 category and 1000 product. I have used bogus package for fake data.(check on Github)

Let’s make some requests and write Our Linq methods:

  1. In this request we have accessed the all products and filtered with Where method and took products which starts with ‘S’ letter.
[HttpGet("startsWith'S'Query")]
public ActionResult GetProducts()
{
var data = _context.Products;

var response = data.Where(i => i.Name.StartsWith("s")).ToList();

//Second way to do the same operation
var response2 =
from product in data
where product.Name.StartsWith("s")
select product;


return Ok(response);

//return Ok(response2); // this will return the same data
}

2. In this request we get the product list again but we ordered it by product Name A-Z Alphabetically.

[HttpGet("orderByAscending")]
public ActionResult GetProductsOrderByAscending()
{
var data = _context.Products;

var response =
from product in data
orderby product.Name
select product;

return Ok(response);
}

I have added the reverse case to which is ordering by Name [Z-A] check my Github repo to see it!!

3. In this request we are making a join operation and we are getting category too with product.

   [HttpGet("Join Operations")]
public ActionResult GetProductsWithCategoryInformations()
{

var query = from product in _context.Products
join category in _context.Categories
on product.CategoryId equals category.Id
select new { product.Category, product.Name };

return Ok(query);
}

There are too many Linq operations, I can not write them all but you can check from microsoft docs from here.

Especially check this methods: FirstOrDefault, SingleOrDefault, Any, Count.

I didnt write all methods but I have created a repo for you(Dont forget to giving a star to repo :)), go and clone it after cloning go and read microsoft docs and try add more linq queries. Even you can change the scenario. You will learn much better when you code. Go and start to coding.

In conclusion, LINQ (Language Integrated Query) simplifies data manipulation tasks by providing a powerful set of methods. From basic filtering to advanced operations, LINQ streamlines code and enhances readability. The provided examples demonstrate its versatility in scenarios like filtering customers or performing join operations. Now, armed with the knowledge of methods like FirstOrDefault, SingleOrDefault, Any, and Count, you're well-equipped to leverage LINQ in your projects. Dive into the world of LINQ, explore Microsoft docs, and don't forget to check out the GitHub repository for hands-on learning. Happy coding

I am learning a lot while I am writing I hope you learned a lot too while you are reading and enjoyed it. Don’t forget to follow on Medium to keep learning together. See you soon :)

--

--

Server Tombak
Server Tombak

Written by Server Tombak

Software Engineer with a relentless passion for learning and sharing knowledge. Join me on my journey to explore the ever-evolving world of technology.

No responses yet