试图从类中返回一个集合

时间:2011-11-29 20:46:19

标签: c# linq

我有以下类,我想返回特定状态的所有USLocation类:

var usLocations = (from s in GetUSStates() where s.Code == stateCode select s.Locations);

但我一直收到错误:

  

无法隐式转换类型   'System.Collections.Generic.IEnumerable< System.Collections.Generic.IEnumerable< A.Model.USLocation>>'   到'System.Collections.Generic.List< A.Model.USLocation>'。一个明确的   存在转换(你错过了演员吗?)

似乎“选择s.Locations正在回收集合中的集合。我在这里做错了什么?

public class USState
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public IEnumerable<USLocation> Locations { get; set; } 
    public override string ToString()
    {
        return string.Format("{0}:{1} ({2})", Name, Code, Id);
    }
}

public class USLocation
{
    public int Id { get; set; }
    public string Name { get; set; }
}

4 个答案:

答案 0 :(得分:7)

您是select集合而不是单个项目。这就是usLocationIEnumerable的{​​{1}}的原因。尝试使用IEnumerable和(可选)SelectMany

ToList

您将获得var usLocations = GetUSStates().Where(s => s.Code == stateCode).SelectMany(s => s.Locations).ToList(); 的列表。

答案 1 :(得分:1)

您需要使用SelectMany代替Select。

答案 2 :(得分:0)

var usLocations = GetUSStates()
      .Where(state => state.Code == stateCode).Single().Locations;

var usLocations = (from s in GetUSStates()
                   where s.Code == stateCode
                   from l in s.Locations
                   select l);

答案 3 :(得分:0)

var usLocations = GetUSStates().Where(s => s.Code == stateCode).First().Locations;

编辑:您的查询返回一个枚举,其中包含一个州的结果,本身就是位置的枚举。

相关问题