新しい映画タイプを追加するだけの一般的なソリューション。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; }
}