试图从类中返回一个集合

The*_*Guy 0 c# linq

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

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

但我一直收到错误:

无法将类型'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; }
}
Run Code Online (Sandbox Code Playgroud)

Mag*_*tLU 7

您正在select收集而不是单个项目.这就是为什么usLocationIEnumerableIEnumerable秒.尝试使用SelectMany和(可选)ToList:

var usLocations = GetUSStates().Where(s => s.Code == stateCode).SelectMany(s => s.Locations).ToList();
Run Code Online (Sandbox Code Playgroud)

你会得到一份清单USLocation.