You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无显式循环更优雅地拼接二维字符串数组为指定格式?

一行代码实现参数键值对拼接为指定格式

需求:将一组参数与值的配对列表,拼接成「-arg0=val0 -arg1=val1 ... -argN=valN」的格式,要求无需显式循环,用一行代码完成。

现有实现代码

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        var argumentValueList = new string[,]
        {
            {"foo", "bar"},
            {"fop", "bas"},
            {"foq", "bat"}
        };
        
        var parameterList = new List<string>();
        
        for (int i=0;i < argumentValueList.GetLength(0); i++)
        {
            parameterList.Add($"-{argumentValueList[i, 0]}={argumentValueList[i, 1]}");
        }
        
        Console.WriteLine(string.Join(" " ,parameterList));
    }
}

优化后的一行代码实现

利用LINQ的索引生成与映射能力,无需显式循环即可完成拼接:

using System;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        var argumentValueList = new string[,]
        {
            {"foo", "bar"},
            {"fop", "bas"},
            {"foq", "bat"}
        };

        // 核心一行代码
        Console.WriteLine(string.Join(" ", Enumerable.Range(0, argumentValueList.GetLength(0)).Select(i => $"-{argumentValueList[i, 0]}={argumentValueList[i, 1]}")));
    }
}

逻辑说明

  • Enumerable.Range(0, argumentValueList.GetLength(0)):生成对应二维数组每一行的索引序列
  • Select(...):将每个索引对应的键值对,拼接成-键=值格式的字符串
  • string.Join(" ", ...):把所有拼接好的字符串用空格连接,得到最终结果

预期输出

-foo=bar -fop=bas -foq=bat

内容的提问来源于stack exchange,提问作者infinitezero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:05:32