我如何加入三个表并获得所有价值 对于两个表我引用
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();
}
但不希望这种类型的查询加入三个表。有人帮我加入三个表加入
答案 0 :(得分:0)
我不是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);
}
}