LinQ查询单行选择多个数据

时间:2014-11-18 07:13:40

标签: linq entity-framework

我有两个数据表。

表:池塘

Pond_ID              Pond_Owner
 01                    Nasir
 02                    John

表:鱼

Pond_ID                 Fish_Name
 01                       Koi
 01                       Carp
 02                       Cat Fish
 02                       Gold Fish
 02                       Comet
 02                       Magur

注意 Pond_ID 字段是 Pond Table 中的主键 外键 >鱼桌。现在我想写一个LinQ查询到结果,如下面。

预期结果

Pond_ID              Pond_Owner              Fish_Name
  01                  Nasir                   Koi, Carp
  02                  John                    Cat Fish, Gold Fish, Comet, Magur

所以任何人都可以帮我写这个linQ查询。提前谢谢。

2 个答案:

答案 0 :(得分:3)

您必须将它们分组到 PondID OwnerName : <击>

<击>
 var result = from p in db.pond
                 join f in db.Fish on p.Pond_Id equals f.Pond_Id
                 group f by new 
                           { 
                             f.Pond_Id,
                             f.Owner_name 
                           } into g
                 select new 
                          { 
                            Owner = g.Key.Owner_Name, 
                            Fishes = String.Join(",",g.Select(x=>x.Fish_Name))  
                          }

然后迭代结果集:

foreach(var item in result)
{
  Console.WrtieLine(String.Format("Owner Name : {0} , Fishes : {1}",item.Owner,item.Fishes))
} 

<击>

UPDATE:

var result = from p in db.pond
                 join f in db.Fish on p.PondID equals f.PondID
                 group f by new { f.PondID,p.OwnerName } into g
                 select new { Owner = g.Key.OwnerName, Fishes = String.Join(",",g.Select(x=>x.FishName))};

    foreach(var item in result)
    {
     Console.WriteLine(String.Format("Owner : {0} and Fishses : {1}",item.Owner,item.Fishes));
    }

有关详情,请参阅此WORKING FIDDLE EXAMPLE

答案 1 :(得分:1)

您可以在LINQ上执行连接操作,如:

var result = (from p in dbContext.Pond
              join f in dbContext.Fish
              on p.Pond_ID == f.Pond_ID
              select new
              {
              Pond_ID = p.Pond_ID,              
              Pond_Owner = p.Pond_Owner,
              Fish_Name = f.Fish_Name 
}).ToList();

以上查询将执行完整加入。如果要执行左外连接,可以使用DefaultIfEmpty()执行相同的操作:

  var result = (from p in dbContext.Pond
                  join f in dbContext.Fish                  
                  on p.Pond_ID == f.Pond_ID into group1 
                  from g1 in group1.DefaultIfEmpty()
                  select new
                  {
                  Pond_ID = p.Pond_ID,              
                  Pond_Owner = p.Pond_Owner,
                  Fish_Name = g1.Fish_Name 
    }).ToList();