Ned
Ned

Reputation: 1207

Combining lists into an arraylist (C#)

I have a list and I want to copy three other lists into it.

// The main list
List<List<string>> list= new List<List<string>>();

// The lists which I want to combine
ArrayList sublist1= new ArrayList();;
ArrayList sublist2= new ArrayList();;
ArrayList sublist3= new ArrayList();;

What I tried is:

list[0].AddRange(sublist1);
list[0].AddRange(sublist2);
list[0].AddRange(sublist3);

It doesn't work because It is multidimensional list. I need this type of list for the future plans.

How can I accomplist it?

Upvotes: 0

Views: 383

Answers (3)

pabdulin
pabdulin

Reputation: 35255

As already mentioned in comments just use List<string> instead of ArrayList. It has nothing to do about multidimensional arrays, just types mismatch.

Then you say List<List<string>> it basically means create list type, which will contain List<string> as items (the part in angle brackets), so you need to add them, not ArrayLists. Similarly List<string> means type of list which will contain string as items.

Upvotes: 1

Dmitry Khryukin
Dmitry Khryukin

Reputation: 6448

change type of sublists to some IEnumerable<string> (string[] or List<string> or something else)

var sublist1 = new string[] {};
var sublist2 = new string[] {};
var sublist3 = new string[] {};

OR do cast

list[0].AddRange((IEnumerable<string>) sublist1);
list[0].AddRange((IEnumerable<string>) sublist2);
list[0].AddRange((IEnumerable<string>) sublist3);

Because you are trying to use AddRange method of System.Collections.Generic.List<T> and the signature of this method is

public void AddRange(System.Collections.Generic.IEnumerable<T> collection)

so it requires IEnumerable as a parameter.

Upvotes: 1

skub
skub

Reputation: 2306

As in the comments, you need to pass a type that follows IEnumerable. For example, you can change your ArrayLists to List

// The main list
List<List<string>> list = new List<List<string>>();

// The lists which I want to combine
var sublist1 = new List<string>();
var sublist2 = new List<string>();
var sublist3 = new List<string>();

list[0].AddRange(sublist1);
list[0].AddRange(sublist2);
list[0].AddRange(sublist3);

Upvotes: 1

Related Questions