Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / SQL

Any Method

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
11 Aug 2011CPOL1 min read 10.9K   1  
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]
)

This article was originally posted at http://pranayamr.blogspot.com/2011/08/any-mehtod.html

License

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


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
-- There are no messages in this forum --