如何在c#中将字符串列表转换为字符串
问题描述:
public List<Movie> mType(List<string> fType)
{
List<Movie> fMovie = new List<Movie>();
foreach(Movie movie in ListOfMovies)
{
if (fType = movie.Type)//this is where the error is
{
fMovie.Add(movie);
}//end of if
}//end of foreach
return fMovie;
}
无法将类型'string'隐式转换为'System.Collections.Generic.List< string>'
这是我得到的错误,任何帮助将不胜感激
Cannot implicitly convert type 'string' to 'System.Collections.Generic.List<string>'
This is the error i am getting, any help will be appreciated
答
我假设您要检查该电影类型是列表中的一个字符串...
使用列表< T> .Contains(T) [ ^ ]方法...
I assume you want to check that movie type is one of the strings in the list...
Use List<T>.Contains(T)[^] method...
if (fType.Contains(movie.Type))
{
// ...
}
如果 fType
不是很短,那么可以使用 HashSet< string>
来优化:>
If the fType
is not very short, then this can be optimized using a HashSet<string>
:
public List<Movie> mType(List<string> fType)
{
List<Movie> fMovie = new List<Movie>();
HashSet<string> typesMap = new HashSet<string>(fType);
foreach(Movie movie in ListOfMovies)
{
if (typesMap.Contains(movie.Type))
{
fMovie.Add(movie);
}//end of if
}//end of foreach
return fMovie;
}
使用Linq这将是:
And using Linq this would be:
public List<Movie> mType(List<string> fType)
{
HashSet<string> typesMap = new HashSet<string>(fType);
return (from movie in ListOfMovies where typesMap.Contains(movie.Type) select movie).ToList();
}