1

If I have a list of an object called Spendline with two properties, Year and Amount and BudgetID. How can I best convert the following List:

Year      Amount      BudgetID
2000      100         1
2001      100         1
2002      100         1
2003      100         1
2001      100         2
2002      100         2
2003      100         2

To this:

Year      Amount      
2000      100         
2001      200         
2002      200       
2003      200   

Using Linq?

2 Answers 2

4

Looks like you want something like:

var query = items.GroupBy(x => x.Year, x => x.Amount)
                 .Select(g => new { Year = g.Key, Amount = g.Sum() };

Or as a query expression:

var query = from item in items
            group item.Amount by item.Year into g
            select new { Year = g.Key, Amount = g.Sum() };

(Call ToList on the query to get a List<T> of course.)

Sign up to request clarification or add additional context in comments.

Comments

0

I think you can do this with GroupBy and Sum functions

An example of getting this data with a loop might look like this:

foreach(var group in SpendlineList.GroupBy(x => x.Year))
{
   int year = group.Key;
   int ammount = group.Sum(x => x.Ammount);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.