如何检查由于左连接而导致int字段为空

时间:2016-12-21 22:37:35

标签: c# linq left-join

我有以下课程。

class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Bonus
{
    public int EmployeeId { get; set; }
    public int Amount { get; set; }
}

class EmployeeBonus
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Amount { get; set; }
}

我需要进行左连接,这样如果Bonus类中不存在EmployeeId,则Amount应为零。以下是其实施方式

class Program
{
    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>()
        {
            new Employee() { ID = 1, Name = "John" },
            new Employee() { ID = 2, Name = "Doe" },
            new Employee() { ID = 3, Name = "Charles" },
            new Employee() { ID = 4, Name = "Mike"},
        };

        List<Bonus> bonus = new List<Bonus>()
        {
            new Bonus() { EmployeeId = 1, Amount = 10 },
            new Bonus() { EmployeeId = 2, Amount = 3 },
        };
        try
        {
            var result = (from e in employees
                          join b in bonus on e.ID equals b.EmployeeId into ps
                          from b in ps.DefaultIfEmpty()
                          select new EmployeeBonus()
                          {
                              ID = e.ID,
                              Name = e.Name,
                              Amount = b.Amount == 0 ? 0 : b.Amount
                          }).ToList();
        }
        catch(Exception ex)
        {

        }
    }
}

但是我在上面的代码中得到以下异常。

  

{&#34;对象引用未设置为对象的实例。&#34;}

     

在   ConsoleApplication2.Program&LT;&GT; c.b__0_4(小于;&GT; f__AnonymousType0 2 <>h__TransparentIdentifier0, Bonus b) in c:\users\john\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 31 at System.Linq.Enumerable.<SelectManyIterator>d__22 3.MoveNext()   在System.Collections.Generic.List 1..ctor(IEnumerable 1集合)
  在System.Linq.Enumerable.ToList [TSource](IEnumerable`1 source)at   ConsoleApplication2.Program.Main(String [] args)in   c:\ users \ john \ documents \ visual studio   2015年\项目\ ConsoleApplication2 \ ConsoleApplication2 \的Program.cs:行   28

解决此问题的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

在这种情况下, ProductDetail pro = new ProductDetail() { ProductDetail_Id = Convert.ToInt32(sdr["ProductDetail_Id"]), ProductName = Convert.ToString(sdr["ProductName"]), ProductDescription = Convert.ToString(sdr["ProductDescription"]), BrandImage = = Convert.ToString(sdr["BrandImage"]), BrandName = = Convert.ToString(sdr["BrandName"]), }; (类型为Bonus)为空。因此,访问b是非法的。

使用前检查b.Amount是否为空。

b

或C#6(虽然我更喜欢前者):

Amount = b != null ? b.Amount : 0

int不能为空。