计算特定郊区C#的总余额

时间:2012-10-04 07:46:30

标签: c# arraylist

   List<Customer> customers = new List<Customer>();
    int id = 0;
    int click = -1;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void AddButton_Click(object sender, EventArgs e)
    {
        Customer rec1 = new Customer("C0020", "Alfred", "Campbelltown", 1500, 2006);
        Customer rec2 = new Customer("C0021", "Ryder", "Liverpool", 2000, 2008);
        Customer rec3 = new Customer("C0022", "Alison", "Strathfield", 5500, 2012);
        Customer rec4 = new Customer("C0023", "Eliza", "Liverpool", 6000, 2012);
        Customer rec5 = new Customer("C0024", "Natsu", "Campbelltown", 2560, 2011);

        customers.Add(rec1);
        customers.Add(rec2);
        customers.Add(rec3);
        customers.Add(rec4);
        customers.Add(rec5);

        click = customers.Count - 1;

    }

如何计算特定郊区的总余额?我可以使用下面的代码计算所有内容的总余额:

        double total = 0;

        foreach (Customer Total in customers)
            total += Total.Balance; //Total Balance

任何想法?感谢

4 个答案:

答案 0 :(得分:1)

在C#&gt; = 3.5中,最简单的方法是使用LINQ:

customers.Where(c => c.Suburb == "whatever").Sum(c => c.Balance);

抱歉,你没有描述你的Customer道具,所以我已经假设了它们。

答案 1 :(得分:1)

您可以使用LINQ的每个组GroupBySum

var suburbGroups = customers
        .GroupBy(c => c.Suburb)
        .Select(g => new { Suburb = g.Key, Balance = g.Sum(c => c.Balance) })
        .OrderByDescending(x => x.Balance);

foreach(var grp in suburbGroups)
    Console.WriteLine("Suburb: {0}  Total-Balance: {1}", grp.Suburb, grp.Balance);

请注意,您需要添加using System.Linq;

演示:http://ideone.com/TQcgE

答案 2 :(得分:0)

假设您的Balance

中有Customer个属性
var bal = customers.Sum(c => c.Balance); // customers is the collection

答案 3 :(得分:0)

使用以下Linq表达式...

var balance=customers.GroupBy(g=>g.suburbname).Select(lg =>new { TotalBalance= lg.Sum(g => g.Balance)});