How to add List<> to a List<> in asp.net

C#asp.netList

C# Problem Overview


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);

C# Solutions


Solution 1 - C#

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);

Solution 2 - C#

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

Solution 3 - C#

  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.

Solution 4 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHasanGView Question on Stackoverflow
Solution 1 - C#AndoView Answer on Stackoverflow
Solution 2 - C#Rob TillieView Answer on Stackoverflow
Solution 3 - C#Fitzchak YitzchakiView Answer on Stackoverflow
Solution 4 - C#JonesieView Answer on Stackoverflow