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

时间:2016-02-15 14:19:34

标签: c# arrays

我已经设法在查询中提取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))

有人能指出我正确的方向吗?我知道这个结构是问题,但我无法思考如何处理这种情况。

1 个答案:

答案 0 :(得分:1)

gathered中没有项目时,您正试图获取元素if(gathered!=null && gathered.Any() && (gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1)) { ... ... } 。添加null和Any检查将有助于您

Bundle exec rake rake-command