0

如果我展示我正在尝试做的事情会更容易:

public struct Server
{
   public string ServerName;
   public string SiteName;
}

List<Server> targetServerList = GetTargetServerList();

targetServerList 将具有以下数据:

SiteName: A
ServerName: 1

SiteName: A
ServerName: 2

SiteName: B
ServerName: 3

SiteName: C
ServerName: 4

目标:我需要创建一个包含以下内容的列表:

SiteName: Site A
ServerNames: 1,2

SiteName: Site B
ServerNames: 3

SiteName: Site C
ServerNames: 4

所以我创建了以下类:

private class ServersPerSite
{
   string ServerNames;
   string SiteName;
}

因此,如果 SiteName 尚不存在,我需要循环并添加一个带有新 SiteName 的新项目,并将 ServerName 添加到其中。如果确实存在,我只需要添加 ServerName:

foreach (Server server in targetServerList)
{
  //??missing code
}

我怎么做?在 Javascript 中非常简单:

  //Separate the servers per site
  var sites=new Object();

  $("#ServerGrid").jqGrid('getGridParam', 'data').forEach(function(row) 
  {
    if(!sites[row.SiteName])
    {
        sites[row.SiteName] = new Array();
    }
    sites[row.SiteName][sites[row.SiteName].length] = row.ServerName;
  }

谢谢!

4

2 回答 2

4

您可以将 LINQ 与GroupBy方法一起使用:

var result = targetServerList
                .GroupBy(s => s.SiteName)
                .Select(g => new ServersPerSite()
                            {
                                SiteName = "Site " + g.Key,
                                ServerNames = string.Join(",", g);
                            });

编辑:结果为Dictionary

targetServerList.GroupBy(s => s.SiteName)
                .ToDictionary(g => "Site " + g.Key,
                              g => string.Joins(",", g));
于 2013-05-15T04:36:50.600 回答
1

在这种情况下,aDictionary<string, string>甚至Dictionary<string, IList<string>>会是更好的选择。

public struct Server
{
   public string ID;
   public string SiteName;
}



private IDictionary<string, IList<string>> servers;

foreach(var server in GetTargetServerList()){
    if(!servers.ContainsKey(server.SiteName) {
        servers.Add(server.SiteName, new List<string>());
    }
    servers[server.SiteName].Add(server.ID);
}
于 2013-05-15T04:44:56.937 回答