【发布时间】:2014-05-08 19:48:57
【问题描述】:
我正在使用 LINQ 执行自定义查询,该查询根据我的语句返回一个匿名类型列表:
var currUnitFaster = (from unit in pacificRepo.Units
join loc in pacificRepo.GeoLocations on new { unit.geo_location.Latitude, unit.geo_location.Longitude } equals new { loc.geo_location.Latitude, loc.geo_location.Longitude }
join st in pacificRepo.UnitStatuses on unit.c_number equals st.c_number
select new {
index = "0",
unit.c_number,
unit.serial_number,
unused = "0",
unit.ip_address,
unit.build_version,
status = (st.status == Pacific.Domain.Entities.UnitStatus.Statuses.COMPLETE) ? "<font color=\"green\">" + st.stage + "</font>" : "<font color=\"red\">" + st.stage + "</font>",
location = (loc==null) ? "Unknown" : loc.city + ", " + loc.state_abbrv,
unit.location_at_address,
latitude = unit.geo_location.Latitude,
longitude = unit.geo_location.Longitude
}).ToList();
因此,列表中返回的每个元素都是匿名类型:
currUnitFaster[0].ToString() ==> "{ index = 0, c_number = J0000014, serial_number = A2F0JA02, unused = 0, ip_address = 169.254.0.9, build_version = J1, status = <font color=\"green\">Link</font>, location = San Jose, CA, location_at_address = FCC, latitude = 37.390791, longitude = -121.905775 }"
我想要一个值列表,而不是匿名类型列表。这样:
currUnitFaster.First()[0] ==> "0"
currUnitFaster.First()[1] ==> "J0000014"
currUnitFaster.First()[2] ==> "A2F0JA02"
...
最简单的方法是什么?我知道我可以简单地创建一个列表,然后遍历currUnitFaster 中的每个元素并手动将其添加到该列表中。我想知道是否有一些更清洁的转换或基于铸造的方法来做到这一点。
编辑:我已采纳 Selman 的建议,将 select new 更改为 select new object[]。 但是,我现在在尝试运行查询时遇到以下异常:
Exception: {"Unable to cast the type 'System.Nullable`1[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."}
【问题讨论】: