【问题标题】:How do this item replacement in List as simple as possible using Linq with C#? [duplicate]如何使用带有 C# 的 Linq 尽可能简单地替换 List 中的此项? [复制]
【发布时间】:2019-06-29 19:51:40
【问题描述】:

列表中的数字包含一些值,例如:

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

这段代码的目标是

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

2) 复制每个项目,channel == 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();

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

【问题讨论】:

  • 如果您愿意,可以消除result 集合。只需在您的第一个 foreach 循环中添加一个 if 语句。也许像if (item % 1 != channel) { /* both Add calls */ }
  • 是否需要彼此精确地重复 2 个?
  • @ThomasWeller 是的

标签: c# list linq replace transform


【解决方案1】:

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

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

    }
}

输出:

3,3,1,1,44,44

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

【讨论】:

  • 为了进一步简化,可以在模数比较中使用通道并使用数组而不是列表来创建重复项:var result = numbers.Where((n, i) =&gt; i % 2 == channel).SelectMany(n =&gt; new [] { n, n }).ToList();
猜你喜欢
  • 2012-09-14
  • 1970-01-01
  • 2011-10-16
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
相关资源
最近更新 更多