简体   繁体   中英

Lists<> with multiple lists c#

I am searching for a solution to create List<> of Lists with different data types like List<List<int>,List<double>,List<string>> list;

or a List<> with multiple data types like List<int,double,string> list;

In all seriousness... why?

The code which consumes these structures is going to be confusing and difficult to support. It really, really will.

If you have a custom structure to your data, create a custom object to represent that structure. Something like this:

class MyThing
{
    public int Widget { get; set; }
    public double Foo { get; set; }
    public string Something { get; set; }
}

Use actual meaningful names for your values/types/etc. of course, because that's the entire point of doing this.

Then just have a list of those:

var things = new List<MyThing>();

As your structure continues to change and grow, you build the logic of that structure into the object itself , rather than into all of the consuming code which uses it. The code which uses it then more closely approximates the semantics of the operations it's trying to perform, rather than a dizzying assortment of syntactic operations.

You can make a list of lists by

List<List<int>>

To have a list with multiple data types you could use a Tuple which can take up to 8 items.

List<Tuple<string, int>>
List<Tuple<string, string, int>>

You could even go crazy and do the following

Tuple<List<int>, int, int> tuple = new Tuple<List<int>, int, int>(new List<int>(), 2, 3);

May be you can do like this

 public class Helper
    {
        public object value;
        private string Type;
    }

then create list

List<Helper> myList=new List<Helper>();

use like this

myList.Add(new Helper {value = 45,Type = "int"});
myList.Add(new Helper {value = 45,Type = "int"});
myList.Add(new Helper {value = "hello",Type = "string"});

and the covert according to Type .

If I'm understanding you correctly, I think you need a little helper class:

public class MyInfo {
    public int MyInt32 { get; set; }
    public double MyDouble { get; set; }
    public string MyString { get; set; }
}

Then, make a list of those: var myList = new List<MyInfo>() .

You can also use a List<Tuple<int, double, string>> , but I would recommend creating your own class if the scope of usage is wider than a single class, because Tuples properties aren't very descriptive as to what they are: Item1 , Item2 , Item3 ...

解决此问题的最佳方法是使用Interface,您可以在此处找到多种数据类型的解决方案列表

You can use ArrayList - the old non generic list. THis allows you to put anything in it, int, string, FooObject, bool,....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM