如何创建List并验证列表是否已经包含项目

本文关键字:列表 验证 是否 项目 包含 class 何创建 创建 List | 更新日期: 2023-09-27 18:13:30

如果我显示我正在尝试做的话就容易了:

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
}

我该怎么做?非常简单:

  //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;
  }

谢谢!

如何创建List<class>并验证列表是否已经包含项目

您可以使用LINQ与GroupBy方法:

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

Edit: result as Dictionary

targetServerList.GroupBy(s => s.SiteName)
                .ToDictionary(g => "Site " + g.Key,
                              g => string.Joins(",", g));

在这种情况下,Dictionary<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);
}