有没有一种方法来定义一个包含两个元素的字符串数组的List<>?

8

我想构建一个二维字符串数组,其中一个维度的长度为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[,] 

数组怎么办?

6个回答

20

你可以这样做。

List<KeyValuePair<string, string>>

这个想法是键值对将模仿你复制的字符串数组。


4

好的,你可以相对容易地编写一个扩展方法来实现它。类似这样(仅稍微测试过):

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>

有点复杂,但应该能工作。(显然,实现还需要一些改变,但基本原理相同。)

非常好!我仍然很感兴趣,是否有可能以某种方式定义List<>,以强制其仅接受两个元素的字符串数组? - Alexander Prokofyev
无法在编译时或使用List<T>本身完成此操作。还有另一个类(暂时记不起名称),它允许您在添加条目时验证条目,但这仅在执行时进行。 - Jon Skeet

2
唯一的方法是自己实现ToArray()函数。您可以在自己的集合(例如StringTupleCollection)中实现它。这可以与ArrayList相同(即根据需要增加内部数组的大小)。
但我不确定[x,2][x][2](甚至List<string[2]>)的优势是否足以值得这样做的努力。
您还可以编写一个StringTupple类,如下所示:
public class StringTupple : KeyValuePair<string, string>
{
}

1
您可以使用结构体。在手动比较XML节点时,我就是这样做的。
private struct XmlPair
{
    public string Name { set; get; }
    public string Value { set; get; }
}

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

0

这是不可能通过 List<string[]> 实现的,因为类型 string[,]string[] 不同。


0

当我需要在控制器中检索复选框的值时,KeyValuePair对我没有起作用,因为我的model.Roles列表为空。

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

KeyValuePair结构没有默认的无参构造函数,因此无法由模型绑定器实例化。我建议为您的视图创建一个自定义模型类,该类仅具有这些属性。ASP.NET MVC 3将类型KeyValuePair绑定到ViewModel的用户控件

我在以下链接中找到了一个不使用html helper的checkboxlist实现MVC3.0中的CheckboxList


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接