如何在c#中将字符串列表转换为字符串 [英] How to convert list of strings to string in c#
本文介绍了如何在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();
}
这篇关于如何在c#中将字符串列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文