I have a .csv file in which each row represents an association between a software application and a web server. My goal is to fetch a List<Server>
by application, so I'm mapping the .csv to a Dictionary<string, List<Server>>
. I'm using CsvHelper to read the .csv file and map it to objects.
.csv format:
Family | Environment | Name | Application
01 | Dev | WEBD01 | application1
01 | Production | WEBP01 | application1
02 | Dev | WEBD02 | application2
Server class:
public class Server
{
public string Name { get; set; }
public string Family { get; set; }
public string Environment { get; set; }
}
Mapping:
protected override void RefreshData()
{
// _serverDictionary is a class-level Dictionary<string, List<Server>>
_serverDictionary.Clear();
using (TextReader textReader = File.OpenText(_csvFile.FullName))
using (CsvReader reader = new CsvReader(textReader))
{
while (reader.Read())
{
string applicationName = reader.GetField<string>("Application");
Server server = reader.GetRecord<Server>();
if (_serverDictionary.ContainsKey(applicationName))
_serverDictionary[applicationName].Add(server);
else
_serverDictionary.Add(applicationName, new List<Server> { server });
}
}
}
Fetching:
public IEnumerable<Server> GetByApplication(string applicationName)
{
List<Server> servers = new List<Server>();
_appServers.Where(pair => pair.Key.EqualsIgnoreCase(applicationName))
.ForEach(pair => servers.AddRange(pair.Value));
return servers;
}
Concerns:
- Is a
Dictionary
the best data structure to use in the first place? - I feel that both the mapping code and the fetch code could be more efficient by better utilizing LINQ projection.
serverDictionary
is local to theRefreshData
method so it actually does nothing. Is this really what you have? \$\endgroup\$Dictionary
. \$\endgroup\$