开发者

Multiple objects in list, C#

I'm looking for something similar 开发者_如何学编程to List<T>, that would allow me to have multiple T. For example: List<TabItem, DataGrid, int, string, ...> = new List<TabItem, DataGrid, int, string, ...>().


If you are using .NET 4, you could have a List<Tuple<T1, T2, ...>>

Otherwise, your choice is to implement your own type.


Create a class that defines your data structure, and then do

var list = new List<MyClass>();


Normally you'd just have List<MyClass> where MyClass had all those other ones as members.


If it can have any old type, then you need to use an ArrayList.

If you know ahead of time what you'll have in there, then you should either create your own structure, or use a Tuple.


Looks like you're after List<object>?


Tuples are best if you are using .net 4.0. But if you are working 3.5 or below, multidimensional object array is good. Here is the code. I have added 3 different types in a object array and I pushed the same to list. May not be the best solution for your question, can be achieved with object array and list. Take a look at the code.

class Program
{
    static void Main(string[] args)
    {
        object[,] OneObject = new object[1,3]{ {"C Sharp",4,3.5 }};
        List<object> MyList = new List<object>();
        MyList.Add(OneObject);
        object[,] addObject = new object[1,3]{{"Java",1,1.1}};
        MyList.Add(addObject);

        foreach(object SingleObject in MyList)
        {
            object[,] MyObject = (object[,])SingleObject;

            Console.WriteLine("{0},{1},{2}", MyObject[0, 0], MyObject[0, 1], MyObject[0, 2]);
        }  

        Console.Read();
    }
}


Instead of trying in C# 4, you can give the old version features a chance here.

It seems you don't need a strongly typed collection here, in that case ArrayList is the best option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜