TransWikia.com

How to aggregate data, pass and fail as final result?

Stack Overflow Asked by user584018 on November 23, 2020

I have a list of result either having or not having Data plus has Pass and Fail like below,

var results = new List<Result>
{
    new Result{Data = new Data{Name = "A"}, Pass = 1, Fail = 0},
    new Result{Data = new Data{Name = "B"}, Pass = 3, Fail = 1},
    new Result{Pass = 1, Fail = 0}
};

I need to aggregate data and need this as final result output,

var finalResult = new FinalResult
{
    Datas = new List<Data> { new Data { Name = "A" }, new Data { Name = "B" } },
    TotalPass = 5,
    TotalFail = 1,
    Divident = 5/1
}

I tried something like below, but totalPass and totalfail, are not coming correct. Plus, how to aggregate Data?

int totalPass = 0;
int totalfail = 0;

var finalResult = new FinalResult();

foreach (var r in results)
{
    totalPass += r.Pass;
    totalfail += r.Fail;
}

finalResult.TotalFail = totalPass;
finalResult.TotalFail = totalfail;
finalResult.Divident = totalPass / totalfail;

Here are the two classes:

public class FinalResult
{
    public List<Data> Datas { get; set; }
    public int TotalPass { get; set; }
    public int TotalFail { get; set; }
    public int Divident { get; set; }
}

public class Result
{
    public Data Data { get; set; }
    public int Pass { get; set; }
    public int Fail { get; set; }
}

public class Data
{
    public string Name { get; set; }
}

One Answer

You can achieve this easily using LINQ:

var finalResult = new FinalResult
{
    Datas = results.Where(r => r.Data != null).Select(r => r.Data).ToList(),
    TotalPass = results.Sum(r => r.Pass),
    TotalFail = results.Sum(r => r.Fail)
};

// Beware of division by zero and integer division.
finalResult.Divident = finalResult.TotalPass / finalResult.TotalFail;

Notes:

  • You should probably check the value of TotalFail before the division to prevent division by zero.

  • As Groo mentioned in the comments, Divident should probably be declared as double and you should cast one of the parts to double unless you do want Integer Division.

Correct answer by 41686d6564 on November 23, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP