LINQ foreach语句以获取不起作用的项目

时间:2018-12-05 23:46:09

标签: c# linq enumerator

public partial class Form1 : Form
{
    List<Doctor> doctors = new List<Doctor>();
    List<Episode> episodes = new List<Episode>();
    List<Companion> companions = new List<Companion>();
    public Form1()
    {
        InitializeComponent();
        doctorCombo.Enabled = false;
    }

    private void openMenu_Click(object sender, EventArgs e)
    {
        String input;
        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            //Give a title to the popup and a filter for what files to open.  Then opens the created dialogue
            openFileDialog.Title = "Browse Text Files";
            openFileDialog.Filter = "Text|*.txt"; ;
            openFileDialog.ShowDialog();

            //Read the contents of the file into a stream
            var fileStream = openFileDialog.OpenFile();

            //Opens a streamreader
            using (StreamReader reader = new StreamReader(fileStream))
            {
                while ((input = reader.ReadLine()) != null)
                {
                    String[] exploded = input.Split('|');
                    if (exploded[0].Contains("D "))
                    {
                        Doctor d = new Doctor(Convert.ToInt32(exploded[1]), exploded[2], Convert.ToInt32(exploded[3]), Convert.ToInt32(exploded[4]), exploded[5]);
                        doctors.Add(d);
                    }
                    if (exploded[0].Contains("E "))
                    {
                        Episode ep = new Episode(exploded[1], Convert.ToInt32(exploded[2]), Convert.ToInt32(exploded[3]), exploded[4]);
                        episodes.Add(ep);
                    }
                    if (exploded[0].Contains("C "))
                    {
                        Companion c = new Companion(exploded[1], exploded[2], Convert.ToInt32(exploded[3]), exploded[4]);
                        companions.Add(c);
                    }
                }
                reader.Close();
            }
            doctorCombo.Enabled = true;
            doctorCombo.SelectedIndex = 0;
            var doctorsCompanion =
                from currentDoctor in doctors
                join currentCompanion in companions on currentDoctor.debut equals currentCompanion.debut
                select new {currentDoctor.actor, currentDoctor.series, currentDoctor.age, currentCompanion.debut, currentCompanion.name, currentCompanion.actor };


            foreach (var item in doctorsCompanion)
            {
                outputList.Items.Add("");
            }

最后的foreach语句一直说不能对'?'类型的变量进行操作因为“?”不包含“ getenumerator”的公共实例定义 我正在将一个称为“医生”的课程与一个名为“伴侣”的课程合并。

1 个答案:

答案 0 :(得分:0)

您的匿名类型中有两个actor成员:

select new {currentDoctor.actor, /* ... */ currentCompanion.actor };

这是一个错误,因此编译器无法继续。

您必须给他们起不同的名字:

select new { doctor_actor = currentDoctor.actor, /* ... */ 
    companion_actor = currentCompanion.actor };