198

Is there a short way to add List<> to List<> instead of looping in result and add new result one by one?

var list = GetViolations(VehicleID);
var list2 = GetViolations(VehicleID2);

list.Add(list2);
HasanG
  • 12,734
  • 29
  • 100
  • 154

4 Answers4

395

Use List.AddRange(collection As IEnumerable(Of T)) method.

It allows you to append at the end of your list another collection/list.

Example:

List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);
Bidou
  • 7,378
  • 9
  • 47
  • 70
Ando
  • 11,199
  • 2
  • 30
  • 46
16

Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));

Satpal
  • 132,252
  • 13
  • 159
  • 168
Rob Tillie
  • 1,137
  • 8
  • 30
16
  1. Use Concat or Union extension methods. You have to make sure that you have this declaration using System.Linq; in order to use LINQ extensions methods.

  2. Use the AddRange method.

steve richey
  • 497
  • 3
  • 16
Fitzchak Yitzchaki
  • 9,095
  • 12
  • 56
  • 96
9

Use .AddRange to append any Enumrable collection to the list.

Satpal
  • 132,252
  • 13
  • 159
  • 168
Jonesie
  • 6,997
  • 10
  • 48
  • 66