I would like to create a anonymous type that can be iterated, takes a string and a string array. The goal is to create a list of groups and each group contains persons:
I would like to know if something like this Pseudo-Code is possible:
var myAnoty =new List<string, string[]>();
myAnoty.add("Programmers", ["Linus", "Bill", "Anders"]);
myAnoty.add("Users", ["John", "Melissa", "Bert"]);
As Muzz pointed out in the comments my pseudo code above is not using an Anonymous Type. Reed Copsey answer below is using them: var m = new { Group = "Men", Members = new[] { "John", "Tom" } }
Working demo without using anonymous types
The following code works in LinqPad:
void Main()
{
List<Object> myAnoties = new List<Object>();
myAnoties.Add(new Anoty {Group="Men", Member=new string[]{"John","Tom"}} );
myAnoties.Add(new Anoty {Group="Women", Member=new string[]{"Eve","Anna"}} );
myAnoties.Dump();
}
// Define other methods and classes here
class Anoty{
public string Group{get; set;}
public string[] Member{get; set;}
}
Not working using anonymous types
The following code uses anonymous types. But somehow the string array will not work with anonymous types.
var m = new { Group= "Men", Member=string[]{"John","Tom"}};
var w = new { Group= "Women", Member=string[]{"Eve","Anna"}};
List<object> myAnoties = new List<object>();
myAnoties.Add(m);
myAnoties.Add(w);
Is there any way to get something like my Pseudo-Code var x = new List<string,string[]>() or something with anonymous types (like above) going?
Thanks
You can accomplish something like your pseudo-code:
Or, if you want a
List<T>:You can also use arrays within anonymous types:
However, assigning this into a
List<object>will make this effectively unusable, as you’ll have no way to access the items by name anymore. You could place them into aList<dynamic>and access them, however.That being said, I’d strongly recommend reconsidering the goal of using anonymous typing entirely. Using named types is typically preferential for situations where you’re going to store the objects. Anonymous types save a bit of typing in this scenario, but add a huge maintenance cost as they add a lot of complexities, and you lose a lot of safety (ie: not having proper constructors, etc). The extra time required to create a custom type is typically far smaller than the debugging and maintenance costs of using anonymous types over time in scenarios where you will persist the values.