林克加入表

时间:2014-04-21 12:48:38

标签: c# linq

我有以下两个表

T1
==========
tid  pId    bId   desc
1    11     10    xyz
2    9      7     abc
3    11     9     tyy

T2
=========
id   bId   exp
1    10    main
2    9     front
3    10    front
4    8     top
5    10    main2
6    9     newM

我的模型类是

public class test
 {
   public int tid {get; set;}|
   public int bid {get; set:}
   public IEnumerable<T2> t2 {get; set;}

 }

我想编写linq查询,以便我可以选择测试类列表

var records=(from c in T1 
             join y in T2 on c.bid equals y.bid
             where c.id==id
             select {
               ....
              });

我对linq查询有点新意。请告诉我如何编写此查询。 谢谢

2 个答案:

答案 0 :(得分:0)

试试这个:

var records = (from t1 in T1
               join t2 in T2
               on t1.bid equals t2.bid
               where t1.id == id
               select new test { tid = t1.tid, bid = t1.bid });

foreach(var record in records)
{
    record.t2 = (from t2 in T2
                 where t2.bid == record.bid
                 select new T2 { id = t2.id, bid = t2.bid }).ToList();
}

答案 1 :(得分:0)

您似乎需要基本按bIdtid进行分组。

var records = (from c in T1
                join y in T2 on c.bId equals y.bId
                where y.id == id
                select new {c.bId, c.tid, y})
                .GroupBy(t => new { t.bId, t.tid })
                .Select(g => new Result { bid = g.Key.bId, tid = g.Key.tid, 
                          tests = g.Select(gg=>gg.y) }).ToList();