1

我的数据库中有两个表

  1. 服务器表 - 包含 ServerID(字符串数据类型)的列表,ServerID 是主键
  2. 组件表 - 包含组件名称列表,ServerID 是外键

以下查询

var query2 = (from a in this.db.Servers
             join b in this.db.Components
             on a.ServerID equals b.ServerID                        
             select new { a.ServerID, b.Name }).AsEnumerable().Select(x => string.Format("{0}---{1} ",x.ServerID, x.Name)).ToArray();

string[] header = query2;

header[] 将有以下结果

Server X component 1x
Server X component 2x
Server X component 3x
Server Y component 1y
Server Y component 2y
Server Y component 3y
Server Z component 1z
Server Z component 2z
Server Z component 3z

但我想显示结果如下

Server X
component 1x
component 2x
component 3x
Server Y
component 1y
component 2y
component 3y
Server Z
component 1z
component 2z
component 3z

这意味着只拾取不同的 ServerID 一次,然后是相应的组件。为了执行这个,我尝试创建两个查询。第一个查询只返回不同的 ServerID,第二个查询作为上述查询并循环和匹配它。但没有用。好心的帮助

4

3 回答 3

4

使用 group join 按服务器对组件进行分组:

var query = from a in this.db.Servers
            join b in this.db.Components
                 on a.ServerID equals b.ServerID into g
            select new { 
                a.ServerID, 
                Components = g.Select(x => x.Name) 
            };

创建数组:

List<string> result = new List<string>();

foreach(var server in query)
{
   result.Add(server.ServerID);
   foreach(var componentName in server.Components)
       result.Add(componentName);
}

string[] array = result.ToArray();
于 2013-06-14T14:48:48.050 回答
2

我将按 分组ServerID并使用 aSelectMany将每个 ID 与组件列表连接起来:

var query2 = (from a in this.db.Servers
             join b in this.db.Components
             on a.ServerID equals b.ServerID                        
             select new { a.ServerID, b.Name })
             .AsEnumerable()
             .GroupBy(a => a.ServerID)
             .SelectMany(g => (new [] {g.Key}).Concat(g.Select(i=>i.Name)));

string[] header = query2.ToArray();

或者如果你想在服务器上进行分组:

var query2 = (from a in this.db.Servers
             join b in this.db.Components
             on a.ServerID equals b.ServerID  into g
             select new { 
                a.ServerID, 
                Components = g.Select(x => x.Name) 
             })
             .AsEnumerable()
             .SelectMany(g => (new [] {g.ServerID}).Concat(g.Components));
于 2013-06-14T14:55:46.660 回答
1

您可以使用 GroupBy LINQ 运算符指定 ServerID 作为键;结果是一组IGrouping对象,每个对象对应一个 ServerID,每个对象都包含该 ServerID 的记录列表。

尝试:

from a in this.db.Servers
join b in this.db.Components
on a.ServerID equals b.ServerID                        
group b.Name by a.ServerID
于 2013-06-14T14:50:58.817 回答