Methods returning multiple values

Methods - Extract multiple elements

Take() method

The Take() method extracts the first n elements (where n is a parameter to the method) from the beginning of the target sequence and returns a new sequence containing only the elements taken.

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
IEnumerable<int> result = ints.Take(3);

Skip() method

The Skip() method can be thought of as the exact opposite of the Take() method. Where the Take() method, returns a sequence containing the first n elements of the target sequence, the Skip() method "skips" over the first n elements in the sequence and returns a new sequence containing the remaining elements after the first n elements.

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
IEnumerable<int> result = ints.Skip(3);

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.

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

Can you try these for your own collection of other data types like string?

Last updated