Reputation: 370
My goal is to use the data I get and put it in a table. Two columns, one called Name and the other called Region. I am pretty new to c# and found that there is a function called datatable that allows you to do that, but with a little research that is not available in c# core (correct me if I'm wrong please). Therefore I found this thing called dictionaries and tried my best:
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (var rGroup in azure.ResourceGroups.List())
{
// dict.Add("Name", rGroup.Name);
// dict.Add("Region", rGroup.Region.Name);
dict.Add(rGroup.Name, "Name");
dict.Add(rGroup.Region.Name, "Region");
}
foreach (var di in dict)
{
Console.WriteLine("Key = {0}, Value = {1}", di.Key, di.Value);
}
I get the error
System.ArgumentException occurred HResult=0x80070057 Message=An item with the same key has already been added. Key: northeurope
Source= StackTrace: at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at AzureAPi.Program.RunSample(IAzure azure) in C:\Users\solar\documents\visual studio 2017\Projects\AzureAPi\AzureAPi\Program.cs:line 44 at AzureAPi.Program.Main(String[] args) in C:\Users\solar\documents\visual studio 2017\Projects\AzureAPi\AzureAPi\Program.cs:line 72
Can someone help me on what I did wrong? In addition, is this the best and simplest way to approach this?
Upvotes: 1
Views: 2004
Reputation: 247283
I believe you are adding the items incorrectly
foreach (var rGroup in azure.ResourceGroups.List()) {
dict[rGroup.Name] = rGroup.Region.Name;
}
You use the group name as the key and the region as the value.
Other than that you can create a strongly typed object to hold your data
public class MyTableName {
public string Name { get; set; }
public string Region { get; set; }
}
and construct it from the collection.
Note: Using Linq
var data = azure.ResourceGroups.Select(rGroup => new MyTableName {
Name = rGroup.Name,
Region = rGroup.Region.Name
}).List()
foreach (var item in data) {
Console.WriteLine("Key = {0}, Value = {1}", item.Name, item.Region);
}
You could also use an anonymous type
var data = azure.ResourceGroups.Select(rGroup => new {
Name = rGroup.Name,
Region = rGroup.Region.Name
}).List()
foreach (var item in data) {
Console.WriteLine("Key = {0}, Value = {1}", item.Name, item.Region);
}
Upvotes: 1
Reputation: 1053
An approach that is close to your idea could be a List of an object that simply contains your region and name of the region.
Create a class like this
public class Region
{
public string Name { get; set; }
public string RegionName { get; set; }
}
And replace your Dictionary with Region typed List.
List<Region>
Upvotes: 2