1

How could I achieve joining four lists below of different sizes into a single new list. I really don't know how to even tackle this.If I did I would of attempted to post some attempt.

Edit: I should point out the list i am trying to create is not a list of lists per se but rather a list of all the combined lists strings.

List<string[5]> coords_list
List<string[8]> outer_plf_list
List<string[8]> planet_start_plf_list
List<string[5]> planet_plf_list
Ryan Walkowski
  • 311
  • 10
  • 19

3 Answers3

3

For your case, try to use LINQ Concat:

This resulting in List<string[]>

var newlist = coords_list
    .Concat(outer_plf_list)
    .Concat(planet_start_plf_list)
    .Concat(planet_plf_list)

Or if you need List<string> instead, do this:

var newlist = coords_list
    .Concat(outer_plf_list)
    .Concat(planet_start_plf_list)
    .Concat(planet_plf_list)
    .SelectMany(x => x)
    .ToList();

You could also use AddRange as an alternative:

var newlist = new List<string[]>();
newlist.AddRange(coords_list);
newlist.AddRange(outer_plf_list);
newlist.AddRange(planet_start_plf_list);
newlist.AddRange(planet_plf_list);

And if you have List<List<List<string>>> instead of List<string[]> with different string[] sizes, you could use SelectMany to flatten List<List<List<string>>> into List<List<string>>

Ian
  • 30,182
  • 19
  • 69
  • 107
  • Thanks this helped a lot. I've clearly gotten mixed up. I had found concat before but i was ending up with List when i was trying to get List i didnt notice the difference – Ryan Walkowski Feb 27 '16 at 16:06
  • @RyanWalkowski OK, no problem. That's what I wanted to clarify also.. ;) check also Rogey's answer. I think he noticed that too... – Ian Feb 27 '16 at 16:08
3

Do you want a list of string arrays, or just one big list of strings?

For the first case, lan's solution works.

For the latter, use SelectMany;

        List<string[]> p1 = new List<string[]>();
        p1.Add(new String[] { "a", "b" });

        List<string[]> p2 = new List<string[]>();
        p2.Add(new String[] { "c", "d" });
        p2.Add(new String[] { "e", "f" });

        // will contain 6 string items: a, b, c, d, e, f
        var result = p1.Concat(p2).SelectMany(s => s).ToList();
Bogey
  • 4,926
  • 4
  • 32
  • 57
1

You could use the AddRange() method of Lists, like so:

var combinedList = new List<string>();
combinedList.AddRange(coords_list);
combinedList.AddRange(outer_plf_list);
combinedList.AddRange(planet_start_plf_list);
combinedList.AddRange(planet_plf_list);
Froodooo
  • 177
  • 1
  • 9