Firstly, thanks a ton to the StackOverflow community. I am new to C#, and this group has pulled me out of the fire many times!
Issue: I am having a bit of trouble with the C# FindAll method. Specifically, I can’t make it work, and I know it is me…
Stuff that works fine:
public class City
{
public string Name {get;set;}
public string Country {get;set;}
}
public List<City> GetCities()
{
List<City> cities = new List<City>();
cities.Add(new City() { Name = "Istanbul", Country = "Turkey" });
// etc, add a bunch more cities, including multiple entries for
// some cities
return cities;
}
Now what doesn’t work… (It returns all the cities or none (depending on how I fiddle the syntax).
public static List<> ReturnCityList(string CityName)
{
Cities = GetCities;
var RequestedCities = Cities.Findall(s => Name.Equals(CityName));
return RequestedCities
}
What am I doing wrong?
I have read a lot of examples, but am missing something.
Thank you!
Where is
Namecoming from? Did you mean this?Or even
Which does the same thing with a simpler syntax.
You aren’t using the
svariable, i.e., the variable that holds the current element in the iteration. That’s what you likely need to check againstCityName. I doubt your version even compiles. Also…That won’t compile. You can’t use an empty generic argument, you need to specify the return value as
List<City>and then you will need to callToList()on the result of the query. There are a couple other errors as well.Honestly you should probably just return an
IEnumurable<City>as the caller probably doesn’t need to modify the return value, just enumerate it.One more nitpick; method arguments use
camelCaseby convention, notPascalCase, as do local variables.