首页 > 解决方案 > 使用 if 条件时将两个列表数据添加到数组中

问题描述

我有两个列表,一个列表有一些记录(不知道具体的记录数,但不超过 13 条记录),第二个列表只有空值。我在这两个列表上使用 if 条件。并想将这两个列表添加到一个数组中。我正在使用这段代码:

for (int i=0; i>12; i++)
{
    List<string> excList = new List<string>();
    //added column from table, which can varies
    excList.Add((string)column.ColumnName);
    string[] excelList = new string[] {  };
    List<string> stack = Enumerable.Range(excList.Count, 13)
                .Select(z => string.Empty)
                .ToList<string>();
    if (excList.Count > i)
    {
        excelList =  excList.ToArray();
    }
    if (excList.Count <= i)
    {
         excelList = stack.ToArray();
    }
    eCol0 = excelList[0].ToString();
    //show first value, after adding two list in excelList
    response.Write(eCol0);
}

使用此代码,当第二个条件开始并且列表(excList)添加到数组(excelList)中时,excelList仅显示第二个列表数据。

我想将这两个列表(excList 和堆栈)插入到 arrayList(范围为 13)中。但是这两个列表必须在 if 条件的基础上添加,因为我在上面的代码中使用了 if 条件。

标签: c#.net

解决方案


好吧,你永远不会在你的字符串数组 excelList 中添加一些东西。你总是给它分配新的。

使用数组也不是添加值的最佳选择,因为您需要事先知道数组的大小。

如果你真的想要一个包含两个结果的数组,你应该这样做:

        List<string> excList = new List<string>();

        ... fill your excList here and initialize the stack list with whatever you need ...

        excList.AddRange(stack);

        string[] excelList = excList.ToArray();

编辑:正如评论所提到的,你的问题有点令人困惑,你正在使用一个没有明确原因的大循环,并且添加空值也没有任何意义......所以我试图从你想要的东西中找出本质知道

编辑:2 等一下,我想你最后想要一个字符串数组,大小为 13,其中元素至少为 string.empty

            List<string> excList = new List<string>();
            //added column from table, which can varies
            excList.Add((string)column.ColumnName);

            string[] excelList = new string[13];

            for (int i = 0; i < excList.Count; i++)
            {
                excelList[i] = excList[i];
            }

            for (int i = excList.Count; i < 13; i++)
            {
                excelList[i] = string.Empty;
            }

不需要外循环


推荐阅读