填充数组以避免索引超出数组范围错误的方法

问题描述 投票:0回答:4

当我查询时,我预计列表中至少有 183 个项目,但有时提取的结果会导致项目计数低于 183。我当前的修复应该会在计数小于 183 的情况下填充数组。

if (extractArray.Count() < 183) {
    int arraysize= extractArray.Count();
    var tempArr = new String[183 - arraysize];
    List<string> itemsList = extractArray.ToList<string>();
    itemsList.AddRange(tempArr);
    var values = itemsList.ToArray();
    //-- Process the new array that is now at least 183 in length
}

但看来我的解决方案不是最好的。如果有任何其他解决方案能够帮助确保我在提取发生时至少获得 183 件物品,我将不胜感激。

c# arrays data-structures indexoutofboundsexception
4个回答
9
投票

Array 基类实现了 Resize 方法

if(extractArray.Length < 183)
    Array.Resize<string>(ref extractArray, 183);

但是,请记住,调整大小会对性能产生问题,因此仅当您出于某种原因需要数组时此方法才有用。如果可以切换到

List<string>

而且,我想您这里有一个一维字符串数组,因此我使用 Length 属性来检查数组中的有效项目数。


8
投票

我可能会遵循其他人的建议,并使用一个列表。使用“容量”构造函数来提高性能:

var list = new List<string>(183);

然后,每当你获得一个新数组时,就执行此操作(将“”替换为用于填充数组的任何值):

list.Clear();
list.AddRange(array);
// logically, you can do this without the if, but it saves an object allocation when the array is full
if (array.Length < 183)
    list.AddRange(Enumerable.Repeat(" ", 183 - array.Length));

这样,列表始终重用相同的内部数组,减少分配和 GC 压力。

或者,您可以使用扩展方法:

public static class ArrayExtensions
{
    public static T ElementOrDefault<T>(this T[] array, int index)
    {
        return ElementOrDefault(array, index, default(T));
    }
    public static T ElementOrDefault<T>(this T[] array, int index, T defaultValue)
    {
        return index < array.Length ? array[index] : defaultValue;
    }
}

然后像这样编码:

items.Zero = array[0];
items.One = array[1];
//...

变成这样:

items.Zero = array.ElementOrDefault(0);
items.One = array.ElementOrDefault(1);
//...

最后,这是我开始写这个答案的相当麻烦的想法:您可以将数组包装在保证有 183 个索引的 IList 实现中(为了简洁起见,我省略了大部分接口成员实现):

class ConstantSizeReadOnlyArrayWrapper<T> : IList<T>
{
    private readonly T[] _array;
    private readonly int _constantSize;
    private readonly T _padValue;

    public ConstantSizeReadOnlyArrayWrapper(T[] array, int constantSize, T padValue)
    {
         //parameter validation omitted for brevity
        _array = array;
        _constantSize = constantSize;
        _padValue = padValue;
    }

    private int MissingItemCount
    {
        get { return _constantSize - _array.Length; }
    }

    public IEnumerator<T> GetEnumerator()
    {
        //maybe you don't need to implement this, or maybe just returning _array.GetEnumerator() would suffice.
        return _array.Concat(Enumerable.Repeat(_padValue, MissingItemCount)).GetEnumerator();
    }

    public int Count
    {
        get { return _constantSize; }
    }

    public bool IsReadOnly
    {
        get { return true; }
    }

    public int IndexOf(T item)
    {
        var arrayIndex = Array.IndexOf(_array, item);
        if (arrayIndex < 0 && item.Equals(_padValue))
            return _array.Length;
        return arrayIndex;
    }

    public T this[int index]
    {
        get
        {
            if (index < 0 || index >= _constantSize)
                throw new IndexOutOfRangeException();
            return index < _array.Length ? _array[index] : _padValue;
        }
        set { throw new NotSupportedException(); }
    }
}

确认。


2
投票

既然你已经说过需要确保有183个索引,如果没有就需要填充它,所以我建议使用List而不是数组。你可以这样做:

while (extractList.Count < 183)
{
     extractList.Add(" "); // just add a space
}

如果你绝对必须返回到数组,你可以使用类似的东西。


2
投票

我不能说我会推荐这个解决方案,但我不会让它阻止我发布它!无论他们是否愿意承认,每个人都喜欢 linq 解决方案!

使用 linq,给定一个包含 X 个元素的数组,您可以生成一个包含 Y (在您的例子中为 183)个元素的数组,如下所示:

  var items183exactly = extractArray.Length == 183 ? extractArray :
                        extractArray.Take(183)
                                    .Concat(Enumerable.Repeat(string.Empty, Math.Max(0, 183 - extractArray.Length)))
                                    .ToArray();

如果元素少于 183 个,则数组将用空字符串填充。如果元素超过 183 个,数组将被截断。如果恰好有 183 个元素,则按原样使用该数组。

我并不认为这是有效的或者这一定是个好主意。然而,它确实使用了 linq(yippee!)并且很有趣。

© www.soinside.com 2019 - 2024. All rights reserved.