HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Generate sequence in Linq

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
generatelinqsequence

Problem

I want to generate a sequence using Linq that goes from 10 to 100 with a step size of 10. The sequence also must contain a custom value (in the correct order).

This is what I have now, and I'm wondering if there is a smarter way of doing it using Linq expressions.

var pageSize = 25; //number that must be in sequnce if not already, can be anything.
var items = Enumerable.Range(10, 100)     //Generate range           
           .Where(x => x % 10 == 0)       //Take every 10th item
           .Concat(new[] { pageSize })    //Add the custom number
           .Distinct()                    //If the custom number was already in there, remove it
           .OrderBy(x => x);              //Sort the sequence


Result:

10 
20 
25 
30 
40 
50 
60 
70 
80 
90 
100

Solution

Size of initial list in the following code is less:

var x = Enumerable.Range(1, 10)
                  .Select(x_ => x_ * 10)
                  .Concat(new[] {25})
                  .Distinct()
                  .OrderBy(x_ => x_)
                  .ToList();


Otherwise your original code is perfect.

Code Snippets

var x = Enumerable.Range(1, 10)
                  .Select(x_ => x_ * 10)
                  .Concat(new[] {25})
                  .Distinct()
                  .OrderBy(x_ => x_)
                  .ToList();

Context

StackExchange Code Review Q#47332, answer score: 8

Revisions (0)

No revisions yet.