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

标签 c# linq

我的数据库中有两个表

  1. Server 表 - 包含 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,第二个查询作为上述查询并循环并匹配它。但没有用。请帮忙

最佳答案

使用组连接按服务器对组件进行分组:

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

关于c# - 如何从两个数组中过滤相同的字符串并只显示一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17111062/

相关文章:

c# - 调用 WCF 服务时如何触发事件(客户端)

c# - LINQ,Where() 与 FindAll()

c# - 通过在满足条件时添加项目来创建列表

c# - Entity Framework Core 中的内存管理

c# - 在 C# 中进行浅拷贝的最快方法

c# - c#和asp.net有什么关系?

c# - 如何排序 List<Point>

c# - Hadoop远程csharp代码执行

c# - LINQ Count 和 Max 一起使用

c# - 您能否使用 linq 查看两个 IEnumerables 数据是否包含任何公共(public)条目?