3

我有一种搜索方法,它试图将导演名称与一个和/或两个数组中的条目匹配。但是,如果导演在任一数组中有多个电影,我无法弄清楚如何打印多个标题的名称。

现在我的代码如下所示:

if (director == myDVDs[i].Director || director == myBlu[i].Director)
{
    Console.WriteLine("{0}: {1}", i + 1, myBlu[i].Title);

    EndOptions();

}
else if (director != myDVDs[i].Director && director != myBlu[i].Director)
{
    Console.WriteLine("{0} does not have a movie in the database try again",     director);
    Console.Clear();
    Search();
}
4

2 回答 2

4

您可以使用 LINQ Concat,如下所示:

var matching = myDVDs.Concat(myBlu).Where(d => d.Director == director);
int count = 1;
foreach (var m in matching) {
    Console.WriteLine("{0}: {1}", count++, m.Title);
}
于 2012-12-09T21:00:45.353 回答
2

简化添加新电影类型的通用解决方案。要查找使用 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; }
}
于 2012-12-09T21:07:24.877 回答