How to create a list containing a list of different types

Let's say I have these lists:

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

How can I create a list that accepts these lists? how

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

Thank.

+4
source share
2 answers

Instead, I would use the Dictionary compilation:

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 information about the type of list. This can be used for two things:

  • Filter list for a specific type only
  • Know the type List<object>later, just using the key

PS

Depending on what the solution is and what you need to achieve, you can use generics (if the type is known) or dynamic- if the type is unknown, but a dynamic operation at runtime is required if the compiler does not know the type.

+6

, , , .

ofsometype : ISomeInterface
ofsomeanothertype: ISomeInterface
anothertype: ISomeInterface

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

var mainList = new List<ISomeInterface>();
mainList.AddRange(firstlist);
mainList.AddRange(secondlist);
mainList.AddRange(thirdlist);

, ISomeInterface , /.

List<object>, , .

+2

Source: https://habr.com/ru/post/1676830/


All Articles