【发布时间】:2011-05-18 02:47:40
【问题描述】:
每条路线都包含特定顺序的位置。
例如:
NY -> LA 不同于 LA -> NY。
我想编写一个方法来获取位置数组并返回 true 或 false 是否存在具有相同位置和顺序的路线。
我需要使用 linq 到实体和实体框架(Route 和 Location 是实体)来做到这一点。
这是我写的:
public bool IsRouteExists(IList<LocationInRoute> locationsInRoute)
{
Route route = null;
if (locationsInRoute.Count > 0)
{
var query = GetRoutesQuery().
Where(x => x.Locations.Count() == locationsInRoute.Count);
for (int i = 0; i < locationsInRoute.Count; i++)
{
long locationId = locationsInRoute[i].LocationId;
query = query.Where(x =>
x.Locations.ElementAt(i).LocationId == locationId); //THROWS EXCEPTION
}
route = query.SingleOrDefault();
}
return route!=null;
}
我在标记的行中得到以下异常:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
这个异常的原因是什么?
编辑
执行route = query.SingleOrDefault();时发生异常,异常抱怨Where(x => x.Locations.ElementAt(i).LocationId == locationId);。
【问题讨论】:
-
GetRoutes()方法返回什么类型? -
@Kirk Broadhurst:GetRoutesQuery() 返回 IQueryable
。当我使用 GetRoutesQuery().ToList() 时,我没有例外。问题出在我标记的地方。 -
如果没有看到您的完整系统和应用程序,很难判断。我建议您调试、放置一些断点并检查/观察查询、locationsInRoute 和 i 的值。
-
@Kirk Broadhurst:我无法设置断点和调试 SingleOrDefault。
标签: c# .net entity-framework linq-to-entities