亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過增加兩個單獨的列表來創建一個新列表

通過增加兩個單獨的列表來創建一個新列表

C#
慕少森 2023-07-09 10:23:28
我正在嘗試從兩個單獨的列表創建一個新列表,如下所示:List 1 (sCat) = MD0, MD1, MD3, MD4List 2 (sLev) = 01, 02, 03, ROutput-->MD0-01MD0-02MD0-03MD0-RMD1-01MD1-02MD1-03MD1-RMD3-01MD3-02MD3-03MD3-Retc...我想知道是否有一個函數可以產生上述結果。最終,我希望用戶提供列表 2,并將該信息添加到列表 1 中,并存儲為我稍后可以調用的新列表。enter code hereusing System;using System.Collections.Generic;using System.Linq;class Program{    static void Main(string[] args)    {        List<string> sCat = new List<string>();        // add Categories for the Sheets        sCat.Add("MD0");        sCat.Add("MD1");        sCat.Add("MD3");        List<string> sLev = new List<string>();        // add Levels for the Project        sLev.Add("01");        sLev.Add("02");        sLev.Add("03");        sLev.Add("R");        for (int i = 0; i < sCat.Count; i++)        {            // I am getting stuck here.            // I don't know how to take one item from the sCat list and             // add it to the sLev List incrementally.             Console.WriteLine(sCat[i],i);        }        Console.ReadLine();    }}
查看完整描述

3 回答

?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

將從第一個集合中選擇的所有元素的值與另一個集合中包含的元素組合起來:


var combined = sCat.SelectMany(s => sLev.Select(s1 => $"{s}-{s1}")).ToList();

這就像在嵌套for/foreach循環中迭代兩個集合,將每個組合元素添加到新的List<string>:


List<string> combined = new List<string>();


foreach (var s1 in sCat)

foreach (var s2 in sLev) {

        combined.Add(s1 + "-" + s2);

}


查看完整回答
反對 回復 2023-07-09
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

您可以將for循環替換為以下內容:


foreach(var sCatValue in sCat)

{

    foreach(var sLevValue in sLev)

    {

        Console.WriteLine($"{sCatValue}-{sLevValue}");

    }

}


查看完整回答
反對 回復 2023-07-09
?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

  private static void Main()

    {

        List<string> sCat = new List<string>();

        // add Categories for the Sheets

        sCat.Add("MD0");

        sCat.Add("MD1");

        sCat.Add("MD3");


        List<string> sLev = new List<string>();

        // add Levels for the Project

        sLev.Add("01");

        sLev.Add("02");

        sLev.Add("03");

        sLev.Add("R");


        string dash = "-";

        List<string> newList = new List<string>();


        for (int i = 0; i < sCat.Count; i++)

        {

            for (int j = 0; j < sLev.Count; j++)

            {

                newList.Add(sCat[i] + dash + sLev[j]);

            }

        }


        foreach (var item in newList)

        {

            Console.WriteLine(item);

        }


        Console.ReadLine();

    }


查看完整回答
反對 回復 2023-07-09
  • 3 回答
  • 0 關注
  • 187 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號