-1

There is the list numbers contains some values like:

List<short> numbers = new List<short>{ 1, 3, 10, 1, 2, 44, 26};

The goal of this code is

1) to get only % 2 != 0 or only % 2 == 0 items from list, it depends on channel variable if it 0 or 1.

2) duplicate each item, output for channel == 0 should be:

3 3 1 1 44 44

And output for channel == 1 should be:

1 1 10 10 2 2 26 26

This is my code:

var result = channel == 0 
    ? numbers.Where((item, index) => index % 2 != 0).ToList() 
    : numbers.Where((item, index) => index % 2 == 0).ToList();

var resultRestored = new List<short>();

foreach (var item in result)
{
    resultRestored.Add(item);
    resultRestored.Add(item);
}
foreach (var item in resultRestored)
{
    Console.WriteLine(item);
}

This code works, but I think it can be simplified with using Linq. Espesially, I don't like this part of code:

? numbers.Where((item, index) => index % 2 != 0).ToList() 
: numbers.Where((item, index) => index % 2 == 0).ToList();

How do this item replacement in List as simple as possible using Linq with C#?

mr_blond
  • 1,586
  • 2
  • 20
  • 52

1 Answers1

0

Let me know if anything in the following code doesn't make sense.

DotNetFiddle Example

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

public class Program
{
    public static void Main()
    {
        var numbers = new List<short>{ 1, 3, 10, 1, 2, 44, 26};

        var channel1 = numbers
            .Where((n, i) => i % 2 == 0)
            .SelectMany(n => new List<short> { n, n })
            .ToList();

        var channel0 = numbers
            .Where((n, i) => i % 2 == 1)
            .SelectMany(n => new List<short> { n, n })
            .ToList();

        Console.WriteLine(string.Join(",", channel0.Select(s => s.ToString())));
        Console.WriteLine(string.Join(",", channel1.Select(s => s.ToString())));

    }
}

Output:

3,3,1,1,44,44

1,1,10,10,2,2,26,26

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • 2
    To simplify it even more, one could just use the channel in the modulus comparison and use an array instead of a List for creating the duplicates: `var result = numbers.Where((n, i) => i % 2 == channel).SelectMany(n => new [] { n, n }).ToList();` – Kristoffer Lerbæk Pedersen Feb 05 '19 at 22:42