l 使用Where条件
1. 使用Where的显示语句
foreach (var w in whereResult)
Console.WriteLine("ID={0},Name={1}", w.ID, w.Name);
2. 单个条件
表达式
var whereResult = from c in categories
where c.Name == "Vegetables"
select c;
方法
var whereResult = categories.Where(c => c.Name == "Vegetables");
3. 或条件(sql中的or)
表达式
var whereResult = from c in categories
where c.Name == "Vegetables" || c.ID == 001
select c;
方法
var whereResult = categories.Where(c => (c.Name == "Vegetables" || c.ID == 001));
4. 与条件(sql中的and)
表达式
var whereResult = from c in categories
where c.Name == "Vegetables" && c.ID == 001
select c;
方法
var whereResult = categories.Where(c => (c.Name == "Vegetables" && c.ID == 001));
l 连接
1. 内连接
表达式,注意在表达式中的使用join时相等要使用equals
var innerJoinQuery = from c in categories
join prod in products on c.ID equals prod.CategoryID
orderby c.ID
select new { CategoryID = c.ID,CategoryName = c.Name, ProductName = prod.Name};
方法
var innerJoinQuery = categories.Join(products,//要连接的集合
a=>a.ID ,//第一个集合的主键
b =>b.CategoryID , //第二个集合中和第一个集合的主键关联的键,类型需要和第一个集合的主键相同
(c,d) => //c对应于第一个集合中的对象,d对于与第二个集合中的对象,声明2个变量
new {CategoryID = c.ID,CategoryName = c.Name,ProductName = d.Name} //最终返回的结果类型
);
foreach (var item in innerJoinQuery)
{
Console.WriteLine("CategoryID = {0},CategoryName={1},ProductName={2}",item.CategoryID, item.CategoryName, item.ProductName);
}
2. 左连接
表达式
var leftJoinQuery = from c in categories
join prod in products on c.ID equals prod.CategoryID into cp
from t in cp.DefaultIfEmpty(new Product { Name = "Unknown", CategoryID = 006 })
select new { CategoryID = c.ID, CategoryName = c.Name, ProductName = t.Name };
foreach (var item in leftJoinQuery)
{
Console.WriteLine("CategoryID = {0},CategoryName={1},ProductName={2}",item.CategoryID, item.CategoryName, item.ProductName);
}
方法
l 分组
表达式
var groupResults = from c in categories
group c by c.ID;
方法
var groupResults = categories.GroupBy(c => c.ID);
注意显示时的变化:
foreach (var item in groupResults)
{
Console.WriteLine(item.Key);
foreach (var c in item)
{
Console.WriteLine(" ID={0},Name={1}", c.ID, c.Name);
}
}
由于刚开始学习LINQ,对LINQ的理解并不深,难免有不足之处,请大家见谅!