Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list that contains a list of different types

Tags:

c#

Let's say I have such lists :

var firstList = new List<ofsometype>();
var secondList = new List<ofsomeanothertype>();
var thirdList = new List<anothertype>();

How can I make a list that accepts those lists? Like

var mainList = new List<???>();
mainList.Add(firstlist);
mainList.Add(secondlist);
mainList.Add(thirdlist);

Thanks.

like image 868
jason Avatar asked Oct 16 '25 15:10

jason


1 Answers

I'd probably use a Dictionary collection instead :

var firstList = new List<ofsometype>();
var secondList = new List<ofsomeanothertype>();
var thirdlist = new List<anothertype>();

var listsDict = new Dictionary<Type, object>();
listsDict.Add(typeof(ofsometype), firstlist);
listsDict.Add(typeof(ofsomeanothertype), secondlist);
listsDict.Add(typeof(anothertype), thirdlist);

The advantage here is that it gives you the information regarding the type of a list. This could be used for two things :

  1. Filter list for a certain type only
  2. Know the type forList<object> later by simply using the key

P.S.

Depending on what the solution is and what you'd need to achieve you can use generics (if type is known) or dynamics - if type is unknown, but still a dynamic operation at run-time is required if compiler doesn't know the type.

like image 117
Fabjan Avatar answered Oct 19 '25 11:10

Fabjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!