带有查询的.Sum()方法

时间:2014-03-23 22:06:42

标签: c# sql linq

int sum = this.baseClass.PhoneCalls.Sum(phonecall => phonecall.Seconds);

        Show(this.baseClass.PhoneCalls
            .Where(phonecall => this.baseClass.Employees
                .Where(employee => employee.Department.Name.Equals("Finanzas"))
                .Any(employee => employee.TelephoneNumber.Equals(phonecall.DestinationNumber)));

您好,

我试图为某个特定部门的电话拨打一笔款项,但我只是总结了所有电话,而没有为部门过滤。

我无法弄清楚如何将该和变量包含在Show()中,所以它只是将来自该特定部门的人的电话号码相加。

(员工)

public class Employee {

    public Employee(string name, string surname, DateTime dateOfBirth, string telephoneNumber, string email, string province, Office office) {
        Name = name;
        Surname = surname;
        Email = email;
        TelephoneNumber = telephoneNumber;
        DateOfBirth = dateOfBirth;
        Province = province;
        Office = office;
    }

    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string TelephoneNumber { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Province { get; set; }
    public Office Office { get; set; }
    public Department Department { get; set; }
    public int Age { get { return (DateTime.Now - DateOfBirth).Days / 365; } }

    public override string ToString() {
        return String.Format("[Employee: {0}]", Name);
    }
}

(PhoneCall)

public class PhoneCall {

    public DateTime Date { get; set; }

    public string SourceNumber { get; set; }    

    public string DestinationNumber { get; set; }   

    public int Seconds { get; set; } 

    public override string ToString() {
        return String.Format("[Phone call: from {0} to {1}]", SourceNumber, DestinationNumber);
    }
}

(部)

public class Department {

    public Department(string name, IEnumerable<Employee> employees) {
        Name = name; 
        Employees = employees;
    }

    public string Name { get; private set; }

    public IEnumerable<Employee> Employees { get; private set; }

    public override string ToString() {
        return String.Format("[Department: {0}]", Name);
    }
}

问候。

1 个答案:

答案 0 :(得分:0)

我猜您遇到了麻烦,因为Any会返回bool ..您要过滤..所以向Where添加另一个条件,然后Sum之后:

Show(this.baseClass.PhoneCalls
        .Where(phonecall => this.baseClass.Employees
            .Where(employee => employee.Department.Name.Equals("Finanzas") &&
                               employee.TelephoneNumber.Equals(phonecall.DestinationNumber)))
    .Sum(phonecall => phonecall.Seconds));