Linq查询
this article is something about how you use C# to query data using linq, How you translate the normal SQL into the Linq. I am gonna do it step by step.
Before I start this, Let me make some preparation----create two tables for the coming demonstration.
create table Users |
( |
id int identity primary key , |
FirstName nvarchar( max ), |
LastName nvarchar( max ), |
Email nvarchar( max ), |
DisplayName nvarchar( max ), |
Address1 nvarchar( max ), |
Address2 nvarchar( max ), |
Password nvarchar( max ), |
) |
|
create table UserClient |
( |
ID int identity primary key , |
UserId int , |
MobileNo nvarchar( max ), |
IMEINo nvarchar( max ), |
IsApproved bit |
) |
the coming demos are all based on those two tables. let me start now.
Content:
- Select
- Select with columns
- Filter the reullt
- Join the two tables
- Order the Data
- Group the data
- Filter the data by IN and NOT IN
- Filter the data by ROW_NUMBER function
1.Select
The Sql is gonna query all the users from the user table(all columns):
Select * from Users
the Linq to do the same function above is
var users = from u in lddc.Users
select u;
2.Select with columns
this is almost same as the first one. but this is designed to query the certain columns(not all columns):
select firstName, lastName from users
the linq query, actually, linq uses the anonymous function to finish this task:
var users = from u in lddc.Users
select new
{
u.FirstName,
u.LastName
};
3.Filter the reullt
As we know, we can use the WHERE to filter the query
select * from users where id>3.
select * from users where firstName like '%Mik%'
select * from users where firstName like'Mik%'
In linq, we still use the Where clause to do it, but according to the dirrerence of the type of the column behind the where, it is gonna get a little difference showing below:
var users = from u in lddc.Users
u.id>3//for integer data
select u;
var users = from u in lddc.Users
u.FirstName.Contains("Mik")//for String data
select u;
var users = from u in lddc.Users
u.FirstName.StartWith("Mik")//for String data
select u;
4.Join the two tables
Inner join. Getting the data which matchs the condition
Outer join. Not only getting the data which matchs the condition, but also get the data of the left table(doesnot match the condition) with setting the column not being found in the right table to null.
An inner join SQL.
select id, firstName,lastName, mobileNo
from user a
inner join
UserClient b
on a.id=b.userid
Linq also uses the join and another word Equals to join two tables:
var users = from u in lddc.Users
join uc in lddc.UserClient
on u.id equals uc.UserId
select new
{
u.id,
u.FirstName,
u.LastName,
uc.MobileNo
}
A outer join SQL:
select id, firstName,lastName, mobileNo
from user a
left join
UserClient b
on a.id=b.userid
The linq query for outer join gets small change with using the DefaultIfEmpty() function:
var users = from u in lddc.Users
join uc in lddc.UserClient
on u.id equals uc.UserId
into otherUsers
from m in otherUsers.DefaultIfEmpty()
select new
{
u.id,
u.FirstName,
u.LastName,
m.MobileNo//here is m but not uc
};
5.Order the Data
We can use the Order by clause with ASC(default) or DESC to order the selected data.
select * from users order by firstName(asc)//ascending
or
select * from users order by firstName desc//descending
Linq query uses the orderby combined with ascending or descending:
var users = from u in lddc.Users
orderby u.FirstName ascending//ascending here can also be hidden, it is the default value.
select u;
var users = from u in lddc.Users
orderby u.FirstName,u.id descending//can also support multiple columns as SQL does
select u;
6.Group data
Group the data to use the aggregate function like MAX,SUM.. one rule is that the columns you want to query should be either in the aggregate function or in the Group By. if not,you will get a syntax error.
SELECT Count(*) as userCount, FirstName
from users group by FirstName
linq is so readable and kind.it converts all you group by column to a key column seeing below:
var users = from u in lddc.Users
group u by u.FirstName into c
select new
{
t1=c.Key,//this very key is a representative of all columns uses to group the selected data
tcount=c.Count()
};
7. Filter the data by IN and NOT IN
SQL:
select * from user where id in(3,4)
select * from user where id not in(3,4)
The linq uses the Contains function to achieve this task. you should predefine the condition list that can support the Contains function,such as array:
int[] preIDs = { 3, 4 };
var users = from u in lddc.Users
where preIDs.Contains(u.id)
select u;
Linq for NOT IN
int[] preIDs = { 3, 4 };
var users = from u in lddc.Users
where !preIDs.Contains(u.id)
select u;
8.Filter the data by ROW_NUMBER function
ROW_NUMBER is a new feature added from the SQL SERVER 2005. We can use it combined with the >=,<= or between to filter the data, especially we can use it to do the customing paging function. it is very helpful.
select * from
(
select row_number() over(order by id) as rowNumber,*
from users) as t
where t.rowNumber between 6 and 10
order by t.rowNumber
Linq can do this using two functions:
- Skip:accept a specified number and return the remaining elements
- Take:Return a specified number of contiguous elements from he start of a sequence
Look how linq makes this:
var users = from u in lddc.Users
select u;
var filterUsers = users.OrderBy(p => p.id).Skip(5).Take(5);