简化添加新电影类型的通用解决方案。要查找使用 LINQ Select()、Where()、SelectMany()的标题,您可能需要添加using System.Linq
以使用这些方法:
var dvds = new List<IMovie>
{
new DvdMovie {Title = "DVD1", Director = "Director1"},
new DvdMovie {Title = "DVD2", Director = "Director1"},
new DvdMovie {Title = "DVD3", Director = "Director2"}
};
var bluerays = new List<IMovie>
{
new BlueRayMovie {Title = "BR1", Director = "Director3"},
new BlueRayMovie {Title = "BR2", Director = "Director3"},
new BlueRayMovie {Title = "BR3", Director = "Director1"}
};
var allMovies = new List<IEnumerable<IMovie>> {dvds, bluerays};
string searchFor = "Director1";
// Main query, all other initialization code and types are below
IEnumerable<string> titles = allMovies.SelectMany(l =>
l.Where(sl => sl.Director == searchFor)
.Select(m => m.Title));
if (titles != null && titles.Count() > 0)
{
// OUTPUTs: DVD1, DVD2, BR3
foreach (var title in titles)
{
Console.WriteLine(title);
}
}
else
{
Console.WriteLine("Nothing found for " + searchFor);
}
类型
public interface IMovie
{
string Director { get; set; }
string Title { get; set; }
}
// TODO: Make immutable.
// Make setter private and introduce parametrized constructor
public class DvdMovie : IMovie
{
public string Director { get; set; }
public string Title { get; set; }
}
// TODO: Make immutable.
// Make setter private and introduce parametrized constructor
public class BlueRayMovie : IMovie
{
public string Director { get; set; }
public string Title { get; set; }
}