c# - 如何使用带有 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 中的此项?
解决方案
如果以下代码中的任何内容没有意义,请告诉我。
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
推荐阅读
- css - 下一页链接的 CSS 选择器在 Scrapy shell 中返回空列表
- python-3.x - 有没有关于“录制脚本后使用 Postman 删除重复请求”的想法
- c++ - 使用缩进输出修改 Logger
- python-3.x - 运行 chrome 驱动程序时权限被拒绝
- can-bus - Canopen 使用 LSS 自动寻址,如何构建系统
- javascript - 使用 discordjs 启动机器人时如何缓存服务器中的所有成员?
- visual-studio-code - 如何阻止 VSCode 在 jupyter 笔记本中的句点(逗号)之后自动提示?
- php - 我可以在没有任何应用批准的情况下使用我的 Facebook 应用在我的页面上发帖吗?
- dynamic - 有什么方法可以在顺序点云数据中找到动态对象点?
- kubernetes - 如何使用 helm 模板中定义的变量在 configmap 中使用的文件中