如何从两个数组中过滤相同的字符串并仅显示一次

本文关键字:串并 字符串 字符 显示 一次 过滤 两个 数组 | 更新日期: 2023-09-27 18:18:30

我的数据库中有两个表

  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,第二个查询与上面的查询一样,循环并匹配它。但是没有成功。请帮助

如何从两个数组中过滤相同的字符串并仅显示一次

使用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();

我将按ServerID分组,并使用SelectMany将每个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));

可以使用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