Tom
Tom

Reputation: 8681

returning multiple column and sum using linq expression

I need to return two fields using a lambda expression. The first one is the sum of the amount field and the second one is CurrentFinancial year. Below is the code that I have written, how do I include CurrentFinancialYear?

var amount = dealingContext.vw_GetContribution
                           .Where(o => o.ContactID == contactId)
                           .Sum(o => o.Amount);
return new Contribution { Amount = amount ?? 0, CurrentFinancialYear =  };

Upvotes: 0

Views: 1077

Answers (3)

user3844214
user3844214

Reputation: 23

Can you try this:

var amount = dealingContext.vw_GetContribution
            .Where(o => o.ContactID == contactId)
            .GroupBy(o=> new { o.CurrentFinancialYear, o.Amount})
            .Select(group =>
                   new { 
                      year= group.Key.CurrentFinancialYear, 
                      sum= group.Sum(x=>x.Amount) 
                       });

Upvotes: 0

codefromcoffee
codefromcoffee

Reputation: 74

Grouping by Year should do the trick:

            from entry in ledger.Entries
            where entry.ContactID == contactId
            && entry.Time.Year == currentFinancialYear
            group entry by entry.Time.Year
            into g
            select new Contribution () 
            {
                Amount = g.ToList ().Sum (e => e.Amount),
                CurrentFinancialYear = g.Key
            };

UPDATE - just return the first/default result...

            (from entry in ledger.Entries
            where entry.ContactID == contactId
            && entry.Time.Year == currentFinancialYear
            group entry by entry.Time.Year
            into g
            select new Contribution () 
            {
                Amount = g.ToList ().Sum (e => e.Amount),
                CurrentFinancialYear = g.Key
            }).FirstOrDefault();

Upvotes: 1

Lali
Lali

Reputation: 2866

First of all use a simple select

var contribution = dealingContext.vw_GetContribution
                              .Where(o => o.ContactID == contactId).ToList();

It will give you a list of type vw_GetContribution

Then use groupby on this list as

var groupedContribution = contribution.GroupBy(b => b.CurrentFinancialYear).ToList();

Now you can iterate through or use this list as

foreach(var obj in groupedContribution.SelectMany(result => result).ToList())
{
      var amount = obj.Amount;
      var Year = obj.CurrentFinancialYear;
}


OR
In single line, you can do all the above as

var contList = context.vw_GetContribution
                           .Select(a => new { a.Amount, a.CurrentFinancialYear })
                           .GroupBy(b => b.CurrentFinancialYear)
                           .SelectMany(result => result).ToList();

I hope this will solve your problem.

Upvotes: 0

Related Questions