Reputation: 123
Can i convert List<int>
to List<List<int>>
in c#?
When I use such construction
List<int>element=new List<int>();
List<List<int>>superElement= new List<List<int>>(element);
I get a fault,but can I do this in another way?
Upvotes: 5
Views: 613
Reputation: 48415
Due to the fact I do not believe the other answers have really put in much effort to help, I am going to post what I believe to be a more complete and useful answer.
To start with, and for completeness I will show how to achieve what was actually trying to be done. To create a List of Lists you can do this:
List<int> element = new List<int>();
List<List<int>> superElement = new List<List<int>>();
superElement.Add(element);
But as it stands, it doesn't make a lot of sense why you would want to do this, and after some comment probing (hope it didn't hurt) we have discovered that you want to pair up an ID with a List of integers. I would suggest taking a different approach to this.
Personally, I would create a class to hold my data, and then create a single List for those items, like so:
public class MyData
{
public int ID {get; set;}
public List<int> MyValues {get;set;}
public MyData()
{
MyValues = new List<int>();
}
}
Then you can do this:
List<int> element = new List<int>();
MyData data = new MyData();
data.ID = 1;
data.MyValues = element;
List<MyData> superElement = new List<MyData>();
superElement.Add(data);
Which would allow querying like so:
MyData data1 = superElement.SingleOrDeafult(x => x.ID == 1);
List<int> element = data1.MyValues;
Assuming you have Linq available.
An alternate method could be to use a dictionary, like so:
Dictionary<int, List<int>> superElement = new Dictionary<int, List<int>>();
superElement.Add(1, element);
where 1
is an ID, which you can call like so:
List<int> element = superElement[1];
Upvotes: 3
Reputation: 70718
Yes. You can use the collection initializer
List<int> element = new List<int>();
List<List<int>> superElement = new List<List<int>> { element };
http://msdn.microsoft.com/en-gb/library/vstudio/bb384062.aspx
Upvotes: 5
Reputation: 7570
If you just want to initialize the List, then
List<List<int>>superElement= new List<List<int>>();
works; if you want it to contain one (empty) element initially then
List<List<int>>superElement= new List<List<int>>{element};
will do it.
Upvotes: 4
Reputation: 6122
You can do it like this:
List<List<int>> superElement = new List<List<int>>();
superElement.Add(element);
Upvotes: 12
Reputation: 17048
Try this :
var element = new List<int>();
var superElement = new List< List<int> >(){ element };
Upvotes: 7
Reputation: 732
List<int>element=new List<int>();
List<List<int>>superElement= new List<List<int>> { element };
That'll work. You can't pass the list in the constructor.
Upvotes: 8