Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning an IEnumerable of IEnumerables into a dictionary

The problem is after running

 reportData = dbContext.FinancialsBySupplierAuditPeriodStatusType
                        .Where(v => v.ReviewPeriodID == reportFilter.ReviewPeriodID && v.StatusCategoryID == reportFilter.StatusCategoryID)
                        .GroupBy(s => new { s.SupplierID })

                        .Select(g => new DrilldownReportItem {
                            SupplierID = g.Key.SupplierID,
                            SupplierName = g.Max(v => v.SupplierName),
                            AccountNo = g.Max(v => v.AccountNo),
                            TempTotals = g.Select(v => new TempTotals { ClaimType = v.TypeDesc ?? "Old Claims", Amount = v.Amount })
                        }).OrderBy(r => r.SupplierName).ToList();

Temp totals is an IEnumerable that contains a IEnumerable of a simple class of

public class TempTotals {
    public string Type { get; set; }
    public decimal? Amount { get; set; }
}

The idea is to then take this data and group it into a dictionary so that i can get a total of all of the amounts with the key being the type.

The end result should look like:

Dictionary<string, decimal> test = new Dictionary<string, decimal>() {
               {"Claim",2 },
               {"Query", 500 },
               {"Normal", 700 }
           };

I know that I could just foreach it however I am looking for a solution using LINQ.

like image 983
Ben Jones Avatar asked Jun 21 '16 11:06

Ben Jones


2 Answers

Try this:

Dictionary<string, decimal?> test =
    reportData
        .SelectMany(rd => rd.TempTotals)
        .GroupBy(tt => tt.ClaimType, tt => tt.Amount)
        .ToDictionary(g => g.Key, g => g.Sum());

Since the type of Amount is decimal? then the dictionary value is also decimal?.

like image 86
Enigmativity Avatar answered Oct 02 '22 19:10

Enigmativity


Try this:

IEnumerable<IEnumerable<TempTotals>> yourCollection;

var dictionary = yourCollection.SelectMany(s => s).ToDictionary(k => k.Type, v => v.Amount);

Where dictionary will be Dictionary<string, decimal>. But you need to be sure that you won't have two TempTotals with the same Type.

like image 30
MaKCbIMKo Avatar answered Oct 02 '22 17:10

MaKCbIMKo