Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

Any Method

4.00/5 (3 votes)
11 Aug 2011CPOL1 min read 10.9K  
Here I am going to discuss about Any method.

Here I am going to discuss about Any method. One purpose of this method is to check whether the collection has element or not.

Example

C#
List<string> members = 
         new List<string>() { "pranay", "Hemang" };
   bool ISCollectionEmpty = members.Any();

So by using method, I get to know my collection has any element or not.
So when I run the above code, I get true in my boolean variable, if there is no element it returns false.

Now consider the below Database Table and LINQ to SQL DBML file.

Department Table

Image 1

Employee Table

Image 2

Image 3

As you can see, there is one to many relationship between Department and Employee.

Problem Statement

Now here, I want to list out only those departments which have employee.

Solution

Most of the people do the group by and make use of the join and then try to find out the department which has a solution.

But the better solution to this is to make use of Any() method available in the System.Linq for the collection as below:

C#
var deptList = from dept in dbcontext.Departments
                           where dept.Employees.Any()
                           select dept;

   foreach (var item in deptList)
   {
      Console.WriteLine(item.Name + " : " + item.Employees.Count());
   }

Output

Image 4

As you can see, the above query fetches those departments only which has employee and removes the departments that don't have any.
I am easily able to get the count of the employees in department using count method.

SQL Query

When you see the SQL profiler or get the query in Visual Studio by watching variable.

SQL
SELECT [t0].[Id], [t0].[Name]
FROM [dbo].[Department] AS [t0]
WHERE EXISTS(
  SELECT NULL AS [EMPTY]
  FROM [dbo].[Employee] AS [t1]
  WHERE [t1].[DeptId] = [t0].[Id]
)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)