I have a list with a lot of objects List<MyObjects>
- Im iterating through this list and reading the objects. Thats all fine. I just relized now, what it would be awesome if I could add 1 more special value to this List - not an Object, just 1 value of something (a string).
I could now create a class like
class Needless
{
public List<MyObjects> MyList { get; set; }
public string MyValue { get; set; }
}
but Im trying to avoid that. I just really need 1 string with an input every List<MyObjects>
Any ideas?
var t = new { TheString = "", TheList = new List<MyObject>() }; var list = t. TheList; var s = t. TheString; But this only really has benefit in the scope of a method.
To add string values to a list in C#, use the Add() method.
Tuple<string, List<MyObject>>
is an option. However, if you are going to use this pairing a lot, I would advise creating a custom class for it to be more explicit - either like you have done, or by deriving List<MyObject>
and adding the string as a property.
If you are working "in scope" you could always make anonymous types:
var t = new { TheString = "", TheList = new List<MyObject>() };
var list = t.TheList;
var s = t.TheString;
But this only really has benefit in the scope of a method. The compiler can give IntelliSense for this and it is strongly-typed at compile time.
Or if you really want to go all out, use ExpandoObject
from System.Dynamic
:
var expando = new ExpandoObject();
expando.List = new List<MyObject>();
expando.TheString = "";
This is typed in-line without any IntelliSense support, and will invoke the DLR. ExpandoObject
simply uses an IDictionary<string, object>
under the hood, so...
var dict = (IDictionary<string, object>)expando;
...is valid.
The last option is a little tongue-in-cheek. It'll work, but the development experience against it isn't ideal compared to other options. That said, we use ExpandoObject
in our test code, but I can't remember why. One can only hope the reasoning was sound, but it was likely a developer getting giddy with new toys...
you can inherit the List and simply add your property, it's a bit cleaner than composite the List inside another class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With