Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Linq和C#尽可能简单地替换列表中的项?_C#_List_Linq_Replace_Transform - Fatal编程技术网

如何使用Linq和C#尽可能简单地替换列表中的项?

如何使用Linq和C#尽可能简单地替换列表中的项?,c#,list,linq,replace,transform,C#,List,Linq,Replace,Transform,列表编号包含一些值,如: List<short> numbers = new List<short>{ 1, 3, 10, 1, 2, 44, 26}; 通道==1的输出应为: 3 3 1 1 44 44 1 1 10 10 2 2 26 26 这是我的代码: var result = channel == 0 ? numbers.Where((item, index) => index % 2 != 0).ToList() : numbe

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

List<short> numbers = new List<short>{ 1, 3, 10, 1, 2, 44, 26};
通道==1的输出应为:

3 3 1 1 44 44
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和C#?

尽可能简单地替换列表中的项目?如果以下代码中的任何内容没有意义,请告诉我

使用系统;
使用System.Collections.Generic;
使用System.Linq;
公共课程
{
公共静态void Main()
{
变量编号=新列表{1,3,10,1,2,44,26};
var channel1=数字
。式中((n,i)=>i%2==0)
.SelectMany(n=>新列表{n,n})
.ToList();
var channel0=数字
。式中((n,i)=>i%2==1)
.SelectMany(n=>新列表{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


如果需要,可以消除
结果
集合。只需在第一个
foreach
循环中放入if语句。也许类似于
if(item%1!=channel){/*两个Add调用*/}
它是否需要前后两个重复项?@ThomasWeller-yes为了进一步简化它,可以在模比较中使用通道,并使用数组而不是列表来创建重复项:
var result=numbers。其中((n,i)=>i%2==channel.SelectMany(n=>new[]{n,n}).ToList()
? numbers.Where((item, index) => index % 2 != 0).ToList() 
: numbers.Where((item, index) => index % 2 == 0).ToList();
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())));

    }
}