Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property to a list?

Tags:

c#

.net

list

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?

like image 624
miri Avatar asked Jul 26 '12 14:07

miri


People also ask

How to add properties to list in C#?

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.

How to add value in list string C#?

To add string values to a list in C#, use the Add() method.


2 Answers

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...

like image 144
Adam Houldsworth Avatar answered Oct 06 '22 01:10

Adam Houldsworth


you can inherit the List and simply add your property, it's a bit cleaner than composite the List inside another class

like image 30
Tamir Avatar answered Oct 06 '22 01:10

Tamir