[RESOLVED] Help with building an array with C# var in a loop
Hi,
I need to build an array of implicit objects in a var object by looping through a List and adding the to the array. For example...
Code:
var data = new[] { new { Name = "China", Value = 1336718015 },
new { Name = "India", Value = 1189172906 },
new { Name = "United States", Value = 313232044 },
new { Name = "Indonesia", Value = 245613043 },
new { Name = "Brazil", Value = 203429773 },};
If I wanted to dynamically add new objects with the Name and Value values above by a looping through an existing List, how would I go about it?
Please someone help :)
Re: Help with building an array with C# var in a loop
Perhaps I am misunderstanding, but are you copying the implicit objects to a typed list or vise versa?
This is what I thought of right away after reading it:
Code:
var data = new[] { new { Name = "China", Value = 1336718015 },
new { Name = "India", Value = 1189172906 },
new { Name = "United States", Value = 313232044 },
new { Name = "Indonesia", Value = 245613043 },
new { Name = "Brazil", Value = 203429773 },}.ToList();
data.Add(new { Name = "Russia", Value = 141930000 });
data.ForEach(dataItem => Console.WriteLine(string.Format("{0} = {1}", dataItem.Name, dataItem.Value.ToString("#,#"))));
You are creating an anonymous type so it won't directly match up to whatever strongly typed list you have unless it is of the same anonymous type. To add it to a list of something else, say you have a class of CountryInfo and it has two properties, Name and Population, then you would do
Code:
data.ForEach(dataItem => countryList.Add(new CountryInfo() { Name = dataItem.Name, Population = dataItem.Value }));
That would populate the existing list of CountryInfo with the anonymouns type data.
Re: Help with building an array with C# var in a loop
Quote:
Originally Posted by
wakawaka
Perhaps I am misunderstanding, but are you copying the implicit objects to a typed list or vise versa?
I want to copy the typed list to implicit objects.
Re: Help with building an array with C# var in a loop
Ok, so
Code:
countryList.ForEach(county => data.Add(new { Name = country.Name, Value = country.Population }));
countryList being a strongly typed List<CountyInfo>, using the previous post as an example.
Re: Help with building an array with C# var in a loop
Thanks mate, I did it a different way, using some logic in the code you posted first. Like this:
Quote:
List<object> newItems = new List<object>();
foreach (var item in items)
{
newItems.Add(new { Name = item.Product.Title, Value = item.Count });
}
return Json(newItems.ToArray());