|
-
Mar 21st, 2024, 05:39 PM
#2
Re: List of Anonymous objects
 Originally Posted by Shaggy Hiker
This whole question is because I'm lazy, but that's the driver of all kinds of things, so that's fine.
I am getting back a datatable with an annoying number of columns. It's not utterly untenable, but it is annoying. I'm turning that into a list of classes to bind to a specific third-party control. The code to do this is pretty compact and unimpressive. The one annoying thing is that I need an actual class with a property for each of the columns returned from the datatable. The set of columns is static, so I could write out such a class fairly quickly with just a bit of tedious work. However, this is for a report on the web. The code is pretty small and tidy, and I have a bit more work to do to get the output to look and behave the way I want, but that's straightforward.
The issue is that once I have this small and tidy project running, I'll then have to turn around and create up to a dozen more, each of which will get a different datatable with a different, large, set of columns. Creating all these very similar projects will be a snap, with the one exception being the creation of that tedious darn class for use in the list. Heck, that class is the ONLY place I have to enter all the field names. I can even make them all strings, though I probably shouldn't. Furthermore, the sole way that this class will be used is as a holder of a datarow in a List<T>.
I don't care how many fields there are and I don't care what the class is called. I only care about the field names, which become the property names, maybe the type (I haven't really decided, yet, though a goodly number of the fields are strings already), and that's it.
That sounds like an anonymous type, or at least a semi-anonymous type. It's probably asking too much, but is it possible to create a list<anonymous>?
It probably won't work anyways, because I'd then have to expose that list via a bindable property, which would mean a property of anonymous type, and that seems a step too far.
You can't return a list on anonymous types, but you can return a list of Tuples e.g.
Code:
static void Main(string[] args)
{
var results = GetStuff();
foreach (var result in results)
{
Console.WriteLine(result);
Console.WriteLine(result.num2);
}
}
static List<(int num1, int num2, string name)> GetStuff()
{
return new List<(int num1, int num2, string name)>
{
(1,2,"a"),
(2,3,"b"),
(3,4,"c"),
};
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|