Linq:从2个数据表中选择,其中第一个表的列id =第二个表的列ID

时间:2012-03-15 14:12:53

标签: c# sql linq datatable

SQL就像

select GeneralData.id, GeneralData.name, GeneralData.last_name, Student.id
from GeneralData Inner JOIN Student ON Student.id=GeneralData.id

GeneralData是dt1 学生是dt2 我想要的是dt3 有一些建议吗?

5 个答案:

答案 0 :(得分:1)

试试这个:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

答案 1 :(得分:1)

 var query =
            from s in db.Student
            from g in db.GeneralData
            where s.id == g.id
            select new
            {
                g.id,
                g.name,
                g.last_name
            };

答案 2 :(得分:1)

var query = from data in dc.GeneralData
join stud in dc.Students in data.id equals stud.id
select new
{
 data.id, data.Name, data.LastName, stud.id
};

答案 3 :(得分:1)

这样的事情:

var result= (
        from general in db.GeneralData
        join student in db.Student
            on general.id=student.id
        select new
        {
            general.id,
            general.name,
            general.last_name,
            studentId=student.id
        }
    );

其中db是linq数据上下文

答案 4 :(得分:1)

作为方法链:

dt2.Where(s=>s.id == 1)
.Select(s=> new {Stud = s, Data= dt1.Where(g=>g.id == s.id)}).First()
.Select(q=> new {q.Stud.id, q.Data.name, q.data.last_name}).FirstOrDefault();