TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# List Concat

This C# program uses Concat to combine two List collections. Concat is an extension method from System.Linq.

List Concat.

Two Lists can be combined. With the Concat extension method, we do this without a loop. Concat is located in the System.Linq namespace. In this example we examine the Concat method on Lists.

Example. The Concat method is available in the System.Linq namespace in new versions of the .NET Framework. To use Concat, you can combine two collections that implement IEnumerable. This includes the List type or the array type.

Also: You can combine a List and an array or two Lists. The element type (string) of both collections must be the same.

C# program that uses Concat method on Lists

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	List<string> list1 = new List<string>();
	list1.Add("dot");
	list1.Add("net");

	List<string> list2 = new List<string>();
	list2.Add("deves");
	list2.Add("!");

	var result = list1.Concat(list2);
	List<string> resultList = result.ToList();
	foreach (var entry in resultList)
	{
	    Console.WriteLine(entry);
	}
    }
}

Output

dot
net
deves
!

Converting back to List. The Concat method returns an IEnumerable type. The "var result" in the code is of that type. You can convert that back into a List with the ToList extension method.

ToList

Summary. If you have two Lists, you can use the Concat method to combine them. For optimal performance, however, using a method such as AddRange would be better if you need a List result. This is because you could avoid calling ToList.

But: In many programs the Concat method provides the best balance between simplicity and implementation.

Concat


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf