TheDeveloperBlog.com

Home | Contact Us

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

C# Intersect

This C# program shows the Intersect method from System.Linq. It computes intersections.

Intersect applies set theory.

It is an extension method from the System.Linq namespace. In set theory, an intersection is the subset of each collection that is found in both collections. The Intersect method here is elegant.

Example. This example program invokes the Intersect method in the System.Linq namespace. Please note how the two using directives at the top of the program specify where the types are located. We use the array initializer syntax.

Array Initializers

Each array has three numbers in it. Both arrays have the numbers 2 and 3, and one other number. The results show that the Intersect method returns these exact numbers: 2 and 3. These are the intersecting numbers.

Arrays

Tip: Intersect here compares elements in the default way for their type. For ints, a simple numeric comparison for equality is done.

Int

C# program that uses Intersect extension method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Assign two arrays.
	int[] array1 = { 1, 2, 3 };
	int[] array2 = { 2, 3, 4 };
	// Call Intersect extension method.
	var intersect = array1.Intersect(array2);
	// Write intersection to screen.
	foreach (int value in intersect)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

2
3

Summary. We examined the Intersect method that is found in the namespace System.Linq in the C# language. We computed the intersecting part of two integer arrays using a declarative syntax, rather than an imperative loop construct.

Also: A declarative syntax is more concise. But an imperative style could improve the efficiency of this particular operation.


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