[英]adding an int value to multi array int list
我得到了這個多數組整數列表,它看起來像這樣:
List<List<int>> multiarray = new() {
new() { 8, 63 },
new() { 4, 2 },
new() { 0, -55 },
new() { 8, 57 },
new() { 2, -120},
new() { 8, 53 }
};
現在假設我想創建它並使用變量添加項目,我將如何做? 我認為它會如下所示:
int value1 = 4
int value2 = 5
ListStat.Add(value1, value2);
但是我收到一條錯誤消息,說我不能使用“添加”方法重載,我應該使用任何其他命令嗎?
由於您的列表的元素類型為List<int>
而不是(int, int)
,因此您不應使用multiarray.Add((value1, value2)
,而應使用以下內容:
int value1 = 4;
int value2 = 5;
multiarray.Add(new List<int> { value1, value2 });
或者,使用目標類型的new
表達式甚至更短:
multiarray.Add(new(){ value1, value2 });
(解題的替代方法,不用multi List,但是比較長)
//Helper
record ListStat (int value1, int value2)
static void Main(string[] args)
{
List<ListStat> lList = new List<ListStat>()
{
new ListStat(8,63),
new ListStat(4,2),
new ListStat(0,-55),
new ListStat(8,57)
};
lList.Add(new ListStat(0, 0)); //Adding values
Console.WriteLine($"({lList[0].value1};{lList[0].value2})"); //Ref to first element
//Ref for all element step by step in lList
foreach (ListStat singleItem in lList)
{
Console.WriteLine($"({singleItem.value1};{singleItem.value2})");
}
}
如果已知您的子列表只有 2 個項目,我強烈建議您使用ValueTuple<...>
而不是List<int>
。 這不僅增強了代碼的可讀性,而且還降低了應用程序的 memory 占用空間和執行速度,因為必須分配的 memory 更少,並且無需為子列表執行追加/添加操作。
可讀性得到增強,因為(1, 3)
等項目會自動解釋為ValueTuple<int, int>
。
生成的代碼應如下所示:
List<(int, int)> multiarray = new() {
(8, 63 ),
(4, 2 ),
(0, -55 ),
(8, 57 ),
(2, -120),
(8, 53 )
};
然后您可以按如下方式添加新項目(注意額外的括號) :
multiarray.Add((value1, value2));
您可以按如下方式顯示您的項目:
foreach ((int, int) tuple in multiarray)
Console.WriteLine($"My list has the items ({tuple.Item1}, {tuple.Item2})");
或使用解構語法:
foreach ((int value1, int value2) in multiarray)
Console.WriteLine($"My list has the items ({value1}, {value2})");
您可能還想命名您的元組元素:
List<(int a, int b)> multiarray = new() {
(8, 63),
(4, 2),
....
};
它允許您使用以下代碼:
int first = multiarray[0].a; // first tuple element of the first list item.
List<T>
class 有一個Add
方法,該方法采用T
類型的單個值。 當您有List<List<T>>
時, Add
成員采用類型為List<T>
的單個值。 您正在嘗試添加兩個T
類型的值,而編譯器不知道如何處理它們。
如果你想讓你的代碼按原樣工作,那么你可以添加一個擴展方法來讓它工作。
嘗試這個:
public static class MyListExtensions
{
public static void Add<T>(this List<List<T>> listList, params T[] items)
{
listList.Add(new List<T>(items));
}
}
現在你的代碼工作得很好:
List<List<int>> ListStat = new()
{
new() { 8, 63 },
new() { 4, 2 },
new() { 0, -55 },
new() { 8, 57 },
new() { 2, -120 },
new() { 8, 53 }
};
int value1 = 4
int value2 = 5
ListStat.Add(value1, value2);
請改用Dictionary<int,List<int>
,在那里您可以根據您的int
鍵找到您的List<int>
並將值添加到該列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.