外连接中的内部异常

时间:2011-11-04 22:57:37

标签: c# linq outer-join

我不知道为什么我的程序不起作用。请问你能帮帮我吗 !我跑的时候有一个内在的例外。

  var peoples = new List<People>();
   peoples.Add(new People { Model = "Mustang", FirstName = "Joe", LastName = "L'indien" });
   peoples.Add(new People { Model = "Corvet", FirstName = "Luc", LastName = "Emince" });
   peoples.Add(new People { Model = "Verron", FirstName = "pierre", LastName = "Uneed" });
   peoples.Add(new People { Model = "Viper", FirstName = "Martial", LastName = "Roste" });
   peoples.Add(new People { Model = "Camaro", FirstName = "Franck", LastName = "Vador" });

   var cars =  this._cars = new List<Car>();
   cars.Add(new Car { Model = "Mustang", Description = "Gros paté" });
   cars.Add(new Car { Model = "Mustang", Description = "Paté" });
   cars.Add(new Car { Model = "Verron", Description = "Très gros paté" });
   cars.Add(new Car { Model = "Viper", Description = "Attention paté" });
   cars.Add(new Car { Model = "Viper", Description = "Attention paté" });

    var PeopleCar = from people in peoples
                     join car in cars on people.Model equals car.Model into outer
                     from car in outer.DefaultIfEmpty()
                     select new
                     {
                           people.FirstName,
                           people.LastName,                                 
                           car.Model,
                           Desc = (people == null) ? "CASSE DE MERDE" : car.Description
                      };

  foreach (var item in PeopleCar)
  {
         textBox1.AppendText(String.Format("Mr {0} {1} a une voiture model {2} qui envoie du {3}"
                + Environment.NewLine, item.FirstName, item.LastName, item.Model, item.Desc));
   }

2 个答案:

答案 0 :(得分:0)

在您的选择定义字段名称中:

               select new
               {
                  FirstName = people.FirstName,
                  LastName = people.LastName,
                  Model = car.Model,
                  Desc = (people == null) ? "CASSE DE MERDE" : car.Description
                };

答案 1 :(得分:0)

因为您正在进行外部联接,car可以是null - 您应该在select中防范它:

           select new
           {
              FirstName = people.FirstName,
              LastName = people.LastName,
              Model = car == null ? null ; car.Model,
              Desc = car == null ? null : car.Description
            };

此外,您没有问,但可以使用集合初始化程序语法:

var peoples = new List<People>()
{
    new People { Model = "Mustang", FirstName = "Joe", LastName = "L'indien" }),
    new People { Model = "Corvet", FirstName = "Luc", LastName = "Emince" }),
    new People { Model = "Verron", FirstName = "pierre", LastName = "Uneed" }),
    ...
};