首先我们还是先建立一个person.cs类
public class person
{
public string name
{ get; set; }
public int age
{ get; set; }
public string sex
{ get; set; }
}
接下来我们往这个person类添加数据:
List<person> plist1 = new List<person>();
plist1.Add(new person { name = "cxx1", age = 24, sex = "男" });
plist1.Add(new person { name = "cxx2", age = 25, sex = "男" });
plist1.Add(new person { name = "cxx3", age = 26, sex = "男" });
List<person> plist2 = new List<person>();
plist2.Add(new person { name = "cxx1", age = 24, sex = "男" });
plist2.Add(new person { name = "cxx2", age = 28, sex = "男" });
plist2.Add(new person { name = "cxx4", age = 27, sex = "男" });
plist2.Add(new person { name = "cxx5", age = 28, sex = "男" });
var query = from person p in plist1
join person per in plist2
on p.name equals per.name
select new
{
名称=p.name,
性别=p.sex,
年龄=p.age
};
gd2.DataSource = query;
gd2.DataBind();
返回的结果是:
备注:这个方法是要查找出 plist1 与 plist2 之中,name名称有相同记录的数据。
接下来我们来看看sql中的左连接left join 在linq中如何实现
还是先来创建两个cs 类。
/// <summary>
/// 手机列表
/// </summary>
public class MobileStore
{
public string mobId
{ set; get; }
public string mobName
{ set; get; }
}
/// <summary>
/// 手机销售表
/// </summary>
public class MobileSale
{
public string Sid
{ set; get; }
public string mobId
{ set; get; }
public string mobName
{ set; get; }
public string price
{ set; get; }
}
List<MobileStore> listStore = new List<MobileStore>();
listStore.Add(new MobileStore { mobId = "1", mobName = "N86" });
listStore.Add(new MobileStore { mobId = "2", mobName = "N82" });
listStore.Add(new MobileStore { mobId = "3", mobName = "N81" });
listStore.Add(new MobileStore { mobId = "4", mobName = "N95" });
listStore.Add(new MobileStore { mobId = "5", mobName = "N85" });
listStore.Add(new MobileStore { mobId = "6", mobName = "N97" });
List<MobileSale> listSale = new List<MobileSale>();
listSale.Add(new MobileSale { Sid="1" ,mobId="1",mobName="N86",price="100"});
listSale.Add(new MobileSale { Sid="2", mobId = "2", mobName = "N82",price="220" });
listSale.Add(new MobileSale { Sid = "3", mobId = "3", mobName = "N81", price = "300" });
var query = from MobileStore m in listStore
join MobileSale sale in listSale
on m.mobId equals sale.mobId into joinm
from j in joinm.DefaultIfEmpty()
select new
{
ID = m.mobId,
名称 = m.mobName,
价格 = j == null ? "暂无数据" : j.price,
};
gd.DataSource = query;
gd.DataBind();
得到的结果是:
备注:在MobileStore中,我们发现,有六种手机型号,而在MobileSale表中,只有3中,那么意思就是说,其它3种型号的手机,在MobileSale中暂时没有相关的数据,所以对应的也就没有价格的数据。
以上就是关于linq多表查询的两个例子。