簡體   English   中英

如何在 C# 中將多個列表的值合並為一個?

[英]How to combine values of several lists into one in C#?

我正在嘗試將不同列表的幾個值合並到一行中。

例如:

  • 列表 A = [1,2,3,4,5,6,7,8,9]
  • 列表 B = [A,B,C,D]
  • 列表 C = [,?,,-]

然后生病 go 循環遍歷所有列表,並且 output 應該是:

  • 線 = [1,A,!]
  • 線 = [2,B,?]
  • 線 = [3,C,-]
  • 行 = [4,D,NULL]
  • 線= [5,NULL,空]
  • 行 = [6,NULL,NULL]...

結果將被添加到一個 object

到目前為止,我嘗試使用 foreach 循環遍歷我的列表,但在調試之后很明顯我的方法無法工作:

foreach (var item in list1){
       foreach (var item2 in list2){
             foreach (var item3 in list3){
                      string line = makeStringFrom(item, item2, item3);
             }
       }
} 

但我不知道如何使它工作。

您還可以使用 LINQ 函數。

var listA = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var listB = new List<string> { "A", "B", "C", "D" };
var listC = new List<string> { "!", "?", "-" };

var result = Enumerable.Range(0, Math.Max(Math.Max(listA.Count, listB.Count), listC.Count))
    .Select(i => new
    {
        a = listA.ElementAtOrDefault(i),
        b = listB.ElementAtOrDefault(i),
        c = listC.ElementAtOrDefault(i)
    }).ToList();

foreach (var item in result)
{
    Console.WriteLine("{0} {1} {2}", item.a, item.b, item.c);
}

結果:

1 A !
2 B ?
3 C -
4 D
5
6
7
8
9

一般的方法是:

  • 找出所有列表的最大長度

  • 然后創建一個循環到 go 從 0 到最大長度-1

  • 檢查每個列表是否包含該項目的索引,如果是,則檢索該值,否則返回 null

  • 根據這些價值觀建立你的生產線

你可以使用這個:

var A = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
var B = new List<string>() { "A", "B", "C", "D" }; 
var C = new List<string>() { "!", "?", "-"};

var lists = new List<List<string>>() { A, B, C };

int count = 0;
foreach ( var list in lists )
  count = Math.Max(count, list.Count);

var result = new List<List<string>>();
for ( int index = 0; index < count; index++ )
{
  var item = new List<string>();
  result.Add(item);
  foreach ( var list in lists )
    item.Add(index < list.Count ? list[index] : null);
}

foreach ( var list in result )
{
  string str = "";
  foreach ( var item in list )
    str += ( item == null ? "(null)" : item ) + " ";
  str.TrimEnd(' ');
  Console.WriteLine(str);
}

我們創建了一個列表列表,因此您可以將其用於任意數量的列表。

接下來我們取這些列表的最大數量。

然后我們按照算法的指示解析它們:

  • 我們創建一個新列表。
  • 我們將此列表添加到列表列表的結果中。
  • 我們在這個新列表中添加了其他每個列表項目,而 null 沒有更多可用項目。

如果您計划管理多個大型列表以優化 memory 字符串連接,則可以使用 StringBuilder。

小提琴片段

Output

1 A !
2 B ?
3 C -
4 D (null)
5 (null) (null)
6 (null) (null)
7 (null) (null)
8 (null) (null)
9 (null) (null)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM