patterncsharpCritical
A generic list of anonymous class
Viewed 0 times
genericlistanonymousclass
Problem
In C# 3.0 you can create anonymous class with the following syntax
Is there a way to add these anonymous class to a generic list?
Example:
Another Example:
var o = new { Id = 1, Name = "Foo" };Is there a way to add these anonymous class to a generic list?
Example:
var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };
List list = new List();
list.Add(o);
list.Add(o1);Another Example:
List list = new List();
while (....)
{
....
list.Add(new {Id = x, Name = y});
....
}Solution
You could do:
There are lots of ways of skinning this cat, but basically they'll all use type inference somewhere - which means you've got to be calling a generic method (possibly as an extension method). Another example might be:
You get the idea :)
var list = new[] { o, o1 }.ToList();There are lots of ways of skinning this cat, but basically they'll all use type inference somewhere - which means you've got to be calling a generic method (possibly as an extension method). Another example might be:
public static List CreateList(params T[] elements)
{
return new List(elements);
}
var list = CreateList(o, o1);You get the idea :)
Code Snippets
var list = new[] { o, o1 }.ToList();public static List<T> CreateList<T>(params T[] elements)
{
return new List<T>(elements);
}
var list = CreateList(o, o1);Context
Stack Overflow Q#612689, score: 496
Revisions (0)
No revisions yet.