[英]How to create a List<class> and verify if list contains item already
如果我顯示要嘗試的方法比較容易:
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;
}
因此,如果站點名稱尚不存在,那么現在我需要循環並使用新的站點名稱添加一個新項目,並在其中添加服務器名稱。 如果確實存在,我只需要添加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;
}
謝謝!
您可以將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));
在這種情況下, 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.