[英]Join three tables using LINQ
如何連接三個表並獲得我引用的兩個表的所有值
using(Dataclasscontext DbContext = new Dataclasscontext())
{
var result = (from t1 in DbContext.tbl1 join t2 in DbContext.tbl2 on t1.id equel t2.id select new {t1.id,t1.name,t2.class,t2.std}).toArray();
}
對於三張桌子我參考
using(Dataclasscontext DbContext = new Dataclasscontext())
{
var result = (from t1 in DbContext.tbl1
from t2 in DbContext.tbl2 where t1.id1 == t2.id1
from t3 in Db`enter code here`Context.tbl3 where t2.id2 == t3.id2).toArray();
}
但不希望這種查詢用於聯接三張表。 有誰幫助我使用join加入三個表
我不是100%地確定您要做什么,但是我認為您想擺脫“起點”。
這里是一個僅將Linq與“經典方法”結合使用的示例:
// Testclasses which will be joined
public class TestClass1
{
public int Id { get; set; }
public string Name1 { get; set; }
}
public class TestClass2
{
public int Id { get; set; }
public string Name2 { get; set; }
}
static void Main()
{
// define some example-data
List<TestClass1> list1 = new List<TestClass1>()
{
new TestClass1() { Id = 1, Name1 = "One1" },
new TestClass1() { Id = 2, Name1 = "Two1" },
new TestClass1() { Id = 3, Name1 = "Three1" }
};
List<TestClass2> list2 = new List<TestClass2>()
{
new TestClass2() { Id = 1, Name2 = "One2" },
new TestClass2() { Id = 2, Name2 = "Two2" },
new TestClass2() { Id = 3, Name2 = "Three2" }
};
// Here the 'magic' happens:
// We perform a join one our 1st list
// We send list2 as list to join with
// We define two key-selectors in lambda-expressions: t1 => t1.Id and t2 => t2.Id
// We form the joined object as anonymous type: (t1, t2) => new { Id = t1.Id, Name1 = t1.Name1, Name2 = t2.Name2}
var joinedList = list1.Join(
list2,
t1 => t1.Id,
t2 => t2.Id,
(t1, t2) => new { Id = t1.Id, Name1 = t1.Name1, Name2 = t2.Name2 }
);
foreach (var item in joinedList)
{
Console.WriteLine("Id: {0}, Name1: {1}, Name2: {2}", item.Id, item.Name1, item.Name2);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.