Back
Close

Using C# LINQ - A Practical Overview

player_one
126.6K views

Methods - Extract multiple elements

Take() and Skip() return consecutive elements at the beginning and end of a sequence, but there are also ways to extract specific elements scattered throughout a given sequence.

Distinct() method

The Distinct() method works the same way as the DISTINCT directive in SQL. It returns a new sequence containing all the elements from the target sequence that are distinct from each other, as determined by the default equality comparer for the data type of the sequence.

For example:

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
// Will contain { 1, 2, 4, 8 }
IEnumerable<int> result = ints.Distinct();

Intersect() method

Intersect() returns a new sequence containing all the elements that are common to both the target sequence and a second sequence provided as a parameter to the method. Both sequences must provide the same data type, and commonality is determined by the default equality comparer for that data type.

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
List<int> filter = new List<int> { 1, 1, 2, 3, 5, 8 };
// Will contain { 1, 2, 8 }
IEnumerable<int> result = ints.Intersect(filter);

Where(<predicate>) method

Where() returns a new sequence containing all the elements from the target sequence that meet a specified criteria.

NOTE: LINQ is showing its SQL roots here. The Where() method is named based on SQL syntax, but acts like the filter() function in Java, JavaScript, Python, etc.

The criteria is passed into Where() as a predicate delegate method that takes a single parameter of type T (where T is the data type of the elements in the IEnumerable<T> sequence) and returns a bool indicating whether or not the passed-in element should be included in the returned sequence.

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
// Will contain { 2, 4, 4, 2 }
IEnumerable<int> result = ints.Where(theInt => theInt == 2 || theInt == 4);

Exercise

In this exercise, make the GetDistinctShortWords() method return the words from the provided sequence that have fewer than four letters in them and are distinct.

Distinct, Intersect, and Where Exercise
using System.Collections.Generic;
using System.Linq;
namespace MultipleValue1
{
public static class DistinctIntersectWhere1
{
// Return all distinct words that have less than four letters in them.
public static IEnumerable<string> GetDistinctShortWords(
IEnumerable<string> words)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants