How to combine values of several lists into one in C#?
You can also use LINQ functions.
var listA = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var listB = new List<string> { "A", "B", "C", "D" };
var listC = new List<string> { "!", "?", "-" };
var result = Enumerable.Range(0, Math.Max(Math.Max(listA.Count, listB.Count), listC.Count))
.Select(i => new
{
a = listA.ElementAtOrDefault(i),
b = listB.ElementAtOrDefault(i),
c = listC.ElementAtOrDefault(i)
}).ToList();
foreach (var item in result)
{
Console.WriteLine("{0} {1} {2}", item.a, item.b, item.c);
}
Result:
1 A !
2 B ?
3 C -
4 D
5
6
7
8
9
Joining two lists together
You could try:
List<string> a = new List<string>();
List<string> b = new List<string>();
a.AddRange(b);
MSDN page for AddRange
This preserves the order of the lists, but it doesn't remove any duplicates which Union
would do.
This does change list a
. If you wanted to preserve the original lists then you should use Concat
(as pointed out in the other answers):
var newList = a.Concat(b);
This returns an IEnumerable
as long as a
is not null.
Related Topics
How to Save/Download Pdf Embedded in Web Page Without a Pdf Filename
How to Reference Assemblies Using Visual Studio Code
Validate Drivers License Numbers
Updating an Object from a List in C#
How to Convert Any Date Format to Yyyy-Mm-Dd
How to Call Another Controller Action from a Controller in MVC
Remove Hours:Seconds:Milliseconds in Datetime Object
How to Pass Parameter from @Url.Action to Controller Function
How to Read Request Body in an ASP.NET Core Webapi Controller
The Ssl Connection Could Not Be Established
Create a C# Method to Generate Auto Increment Id
Linq to Find All Childs Related to Parents Id
Removing Elements from Json Based on a Condition in C#
Calling a Function from Another Class in C#/.Net MVC App
How to Call a Method Daily, At Specific Time, in C#
How to Iterate Through the Following Json Using C#
How to Check If a Datetime Value Is Empty or Not in a Put Request