简体   繁体   English

如何跳过二维数组的某些初始化程序?

[英]How do I skip some of the initializers for a two-dimensional array?

I have the following definition 我有以下定义

static readonly String[,] allItems = {
    { "Alpha", null },
    { "Beta", "Magic" },
    { "Gamma", null },
    // more items follow
}

In the first column all items must be initialized to some string literals. 在第一列中,所有项目都必须初始化为某些字符串文字。 In the second column only a small fraction of items must be initialized to string literals and all others are null. 在第二列中,只有一小部分项目必须初始化为字符串文字,而所有其他均为空。

I now need to add the third column and it will mostly contain null s and I'd be happy to omit typing all of them. 现在,我需要添加第三列,并且该列将主要包含null并且我很乐意忽略所有输入。

Is there a way to somehow omit those null values? 有没有办法以某种方式忽略这些null值?

I'm not sure if this is the answer you are looking for but have you considered using an object instead. 我不确定这是否是您要寻找的答案,但是您是否考虑过使用对象。 You can then give default values and only supply ones that are different. 然后,您可以提供默认值,并且仅提供不同的值。

for example 例如

public class YourObject{    
    public string Name {get;set;}
    public string Value {get;set;}
    public string SomethingElse {get;set;}

    public YourObject()
    {
        //provide defaults here
        SomethingElse = "";
    }

}

Then to create objects you can create like so 然后创建对象,您可以像这样创建

static readonly List<YourObject> allItems = new List<YourObject>{
    new YourObject{ Name = "Alpha" },
    new YourObject{ Name = "Beta", Value = "Magic" },
    new YourObject{ Name = "Gamma", SomethingElse = "Hello" }
    // more items follow
}

Sriram Sakthivel suggested this whilst i was typing ;) 我在打字时,Sriram Sakthivel建议了这个;

Try out list. 试用清单。 that would allow you to add only required elements. 那将允许您仅添加必需的元素。 You can add further elements later on 您可以稍后再添加其他元素

List allList=new List; 列出allList = new列表; allList.Add() allList.Add()

You can create a class and then use a collection: 您可以创建一个类,然后使用一个集合:

class MyClass
{
   public string Prop1 {get;set;}
   public string Prop2 {get;set;}   
   public MyClass(string prop1, string prop2 = null)
   {
       this.Prop1 = prop1;
       this.Prop2 = prop2   
   }
}

Now, you can use a List<T> 现在,您可以使用List<T>

var list = new List<MyClass>()
{
    new MyClass("Alpha"),
    new MyClass("Beta" , "Magic"),
    new MyClass("Gamme")    
}

If you are not sure about number of columns and you want to define just like table then I recommend you using DataTable. 如果您不确定列数,并且想要像表一样定义,那么建议您使用DataTable。 Thus you can define column type and enforce any constraint. 因此,您可以定义列类型并强制执行任何约束。 This way you can even use Linq to manipulate values. 这样,您甚至可以使用Linq来操纵值。

Here is the sample code: 这是示例代码:

DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

//
// Here we add five DataRows.
//
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;

You can write a class modelling a jagged two dimensional array that can be initialized using a collection initializer. 您可以编写一个模拟锯齿状二维数组的类,该类可以使用集合初始化程序进行初始化。 The class has to implement IEnumerable and should have an appropriate Add method: 该类必须实现IEnumerable并应具有适当的Add方法:

class Table<T> : IEnumerable<IEnumerable<T>> {

  readonly List<T[]> rows = new List<T[]>();

  public void Add(params T[] row) {
    rows.Add(row);
  }

  public IEnumerator<IEnumerable<T>> GetEnumerator() {
    return rows.GetEnumerator();
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
  }

}

You can then use this class directly by say implementing an indexer ( public T this[Int32 rowIndex, Int32 columnIndex] { get { ... } } ) but a better solution is probably to create a method that converts the table to an array: 然后,您可以通过实现索引器( public T this[Int32 rowIndex, Int32 columnIndex] { get { ... } } )直接使用此类public T this[Int32 rowIndex, Int32 columnIndex] { get { ... } }但更好的解决方案可能是创建一个将表转换为数组的方法:

public T[,] ToArray() {
  var columnCount = rows.Max(row => row.Length);
  var array = new T[rows.Count, columnCount];
  for (var rowIndex = 0; rowIndex < rows.Count; rowIndex += 1)
    for (var columnIndex = 0; columnIndex < columnCount; columnIndex += 1) {
      var row = rows[rowIndex];
      array[rowIndex, columnIndex] = columnIndex < row.Length
        ? row[columnIndex] : default(T);
    }
  return array;
}

You can then initialize the two dimensional array using this code: 然后,您可以使用以下代码初始化二维数组:

static readonly String[,] allItems = new Table<String> {
  { "Alpha" },
  { "Beta", "Magic" },
  { "Gamma" },
}.ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM