0
   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;

    }

How do i calculate the total balance by particular suburb? I can calculate the total balance of everything by using the code below:

        double total = 0;

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

Any Ideas? thanks

4

4 に答える 4

1

C# >= 3.5 では、LINQ を使用するのが最も簡単な方法です。

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

申し訳ありませんが、あなたはあなたのCustomer小道具を説明していないので、私はそれらを仮定しました.

于 2012-10-04T07:49:34.503 に答える
1

LINQGroupBySum各グループを使用できます。

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

于 2012-10-04T07:54:55.733 に答える
0

クラスにBalanceプロパティがあると仮定しますCustomer

var bal = customers.Sum(c => c.Balance); // customers is the collection
于 2012-10-04T07:53:04.987 に答える
0

次のLinq式を使用...

var balance=customers.GroupBy(g=>g.suburbname).Select(lg =>new { TotalBalance= lg.Sum(g => g.Balance)}); 
于 2012-10-04T07:54:53.430 に答える