ASP.NET/Entity:我的数组索引有问题

本文关键字:数组 索引 有问题 我的 NET Entity ASP | 更新日期: 2023-09-27 18:34:36

我已经设法在查询中提取了FirstorDefault(),但是,数据库中的一些地址类型实际上具有多个地址:因此,我正在尝试构建每个地址的数组。

当前代码:

int counter = 0;
        string queryID = "";
        List<string> busAddr = new List<string>();
        while (counter != busIDs.Count)
        {
            queryID = busIDs[counter];
            var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToArray();
            int gath = 0;
            if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
                {
                    var address = gathered[gath] as tblbus_address;
                    string test = "";
                    while (gath != address.Address1.Length)
                    {
                        var all = address.Address1;
                        test += address.Address1.ToString() + ",";
                    }
                    busAddr.Add(test);
                }
                else
                {
                    busAddr.Add("No address for this type exists...");
                }
                counter++;
                gath++;
            }

我收到错误:

索引超出数组的范围。

在这一行:

if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))

谁能指出我正确的方向?我知道这种结构是问题所在,但我想不出如何处理这种情况。

ASP.NET/Entity:我的数组索引有问题

您正在尝试获取元素gathered[gath]gathered中没有项目时。添加 null 和 Any 的检查将帮助您

if(gathered!=null && gathered.Any() 
  && (gathered[gath] as tblbus_address) != null 
  && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
    ...
    ...
}