I have the following classes below, I want to return all USLocation classes for a specific state:
var usLocations = (from s in GetUSStates() where s.Code == stateCode select s.Locations);
But I keep getting the error:
Cannot implicitly convert type
‘System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<A.Model.USLocation>>’
to ‘System.Collections.Generic.List<A.Model.USLocation>’. An explicit
conversion exists (are you missing a cast?)
Seems like the “select s.Locations is returning a collection within a collection. What am I doing wrong here?
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; }
}
You are
selecting collection instead of single item. That’s whyusLocationisIEnumerableofIEnumerables. Try usingSelectManyand (optionally)ToList:and you’ll get a list of
USLocation.