locked
How to select Distinct fields and a Sum of fields from an ICollection<T> RRS feed

  • Question

  • I have an ICollection<T> where each T contains a string field, FullAddress, and a decimal field, AmountDue, among other things. I need to select a Distinct FullAddress and a Sum of the AmountDue for all records with that FullAddress. My result would be a new List of items containing the unique FullAddress and the Sum. I'm fairly inexperienced with complex Linq statements, which this seems to be (at least to me).
    Monday, April 7, 2014 12:47 PM

Answers

  • If you are comparing the whole of the FullAddress string then you could use a GroupBy clause. In the example bellow test is a List<T> with the properties you described.

    var res = tests
                .GroupBy(t => t.FullAddress)
                .Select(grp => new { FullAddress= grp.First().FullAddress, AmountDue= grp.Sum(t => t.AmountDue)})
                .ToList();

    • Marked as answer by JimNickFL Monday, April 7, 2014 2:22 PM
    Monday, April 7, 2014 1:11 PM

All replies

  • I have an ICollection<T> where each T contains a string field, FullAddress, and a decimal field, AmountDue, among other things. I need to select a Distinct FullAddress and a Sum of the AmountDue for all records with that FullAddress. My result would be a new List of items containing the unique FullAddress and the Sum. I'm fairly inexperienced with complex Linq statements, which this seems to be (at least to me).
    • Merged by Fred Bao Tuesday, April 8, 2014 1:33 AM Duplicate
    Monday, April 7, 2014 12:48 PM
  • If you are comparing the whole of the FullAddress string then you could use a GroupBy clause. In the example bellow test is a List<T> with the properties you described.

    var res = tests
                .GroupBy(t => t.FullAddress)
                .Select(grp => new { FullAddress= grp.First().FullAddress, AmountDue= grp.Sum(t => t.AmountDue)})
                .ToList();

    • Marked as answer by JimNickFL Monday, April 7, 2014 2:22 PM
    Monday, April 7, 2014 1:11 PM
  • Jay,

    That worked great! Thank you.

    One of the problems in determining a solution to a problem like this, is that there are many, or at least several, ways to write a statement that does what is intended.


    • Edited by JimNickFL Monday, April 7, 2014 2:24 PM additional comment
    Monday, April 7, 2014 2:22 PM