簡體   English   中英

有沒有辦法定義兩個元素字符串數組的 List<> ?

[英]Is there a way to define a List<> of two elements string array?

我想構建二維字符串數組,其中一維的長度為 2。與此類似

string[,] array = new string[,]
{
    {"a", "b"},
    {"c", "d"},
    {"e", "f"},
    {"g", "h"}
}

正在做

List<string[]> list = new List<string[]>();

list.Add(new string[2] {"a", "b"});
list.Add(new string[2] {"c", "d"});
list.Add(new string[2] {"e", "f"});
list.Add(new string[2] {"g", "h"});

list.ToArray();

給我

string[][]

但不是

string[,] 

大批。

只是好奇,是否有一些動態構建的技巧

string[,] 

數組不知何故?

你可以這樣做。

List<KeyValuePair<string, string>>

這個想法是鍵值對將模仿您復制的字符串數組。

好吧,你可以很容易地編寫一個擴展方法來做到這一點。 像這樣(只測試非常輕微):

public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source)
{
    if (!source.Any())
    {
        return new T[0,0];
    }

    int width = source.First().Length;
    if (source.Any(array => array.Length != width))
    {
         throw new ArgumentException("All elements must have the same length");
    }

    T[,] ret = new T[source.Count(), width];
    int row = 0;
    foreach (T[] array in source)
    {
       for (int col=0; col < width; col++)
       {
           ret[row, col] = array[col];
       }
       row++;
    }
    return ret;
}

上面的代碼使用 T[] 作為元素類型有點遺憾。 由於通用不變性,我目前無法制作源IEnumerable<IEnumerable<T>>這會很好。 另一種方法可能是引入一個帶有約束的新類型參數:

public static T[,] ToRectangularArray<T,U>(this IEnumerable<U> source)
    where U : IEnumerable<T>

有點毛茸茸的,但它應該工作。 (顯然實現上也需要一些改動,但基本原理是一樣的。)

唯一的方法是自己實現ToArray()函數。 您可以在自己的集合中實現它(即StringTupleCollection )。 這可以與ArrayList一樣工作(即根據需要增加內部數組的大小)。

但是,我不確定[x,2]對於[x][2] (甚至List<string[2]>是否足夠重要以保證付出努力。

您還可以將StringTupple類編寫為:

public class StringTupple : KeyValuePair<string, string>
{
}

你可以只使用一個結構。 我在手動比較 XML 節點時這樣做。

private struct XmlPair
{
    public string Name { set; get; }
    public string Value { set; get; }
}

List<XmlPair> Pairs = new List<XmlPair>();

當我不得不檢索控制器上復選框的值時,KeyValuePair 對我不起作用,因為我的 model.Roles 列表為空。

foreach (KeyValuePair<string, bool> Role in model.Roles){...}

KeyValuePair 結構沒有默認的無參數構造函數,並且不能被模型綁定器實例化。 我為您的視圖推薦一個只有這些屬性的自定義模型類。 ASP.NET MVC 3 將 KeyValuePair 類型的用戶控件綁定到 ViewModel

在 MVC3.0 中的以下鏈接CheckboxList 中找到了不使用 html helper 的復選框列表的實現

這對於List<string[]>是不可能的,因為類型string[,]string[]不同。

暫無
暫無

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

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