首页 > 解决方案 > 如何使用带有 C# 的 Linq 尽可能简单地替换 List 中的此项?

问题描述

列表编号包含一些值,例如:

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

这段代码的目标是

1) 从列表中仅获取 % 2 != 0 或仅 % 2 == 0 项,它取决于通道变量是 0 还是 1。

2)复制每个项目,通道== 0的输出应该是:

3 3 1 1 44 44

通道 == 1 的输出应该是:

1 1 10 10 2 2 26 26

这是我的代码:

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);
}

此代码有效,但我认为可以使用 Linq 对其进行简化。特别是,我不喜欢这部分代码:

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

如何使用带有 C# 的 Linq 尽可能简单地替换 List 中的此项?

标签: c#listlinqreplacetransform

解决方案


如果以下代码中的任何内容没有意义,请告诉我。

DotNetFiddle 示例

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())));

    }
}

输出:

3,3,1,1,44,44

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


推荐阅读