Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3308572
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T21:32:15+00:00 2026-05-17T21:32:15+00:00

I have a generic list of type Element , for example. public class Element

  • 0

I have a generic list of type Element, for example.

public class Element
{
    public string Country { get; set; }
    public string City { get; set; }
    public int Population { get; set; }
}

With the following data.

var elements = new List<Element>
   {
       new Element { Country = "Country A", City = "Barrie", Population = 12 },
       new Element { Country = "Country A", City = "Barrie2", Population = 12 },
       new Element { Country = "Country A", City = "Barrie2", Population = 12 },
       new Element { Country = "Country A", City = "Barrie", Population = 12 },
       new Element { Country = "Country D", City = "Essex", Population = 12 },
       new Element { Country = "Country A", City = "Barrie", Population = 12 },
       new Element { Country = "Country A", City = "Barrie", Population = 12 },
       new Element { Country = "Country D", City = "Essex", Population = 12 },
       new Element { Country = "Country A", City = "Barrie", Population = 12 },
       new Element { Country = "Country A", City = "Barrie", Population = 12 }
   };

Essentially, I’d like a running total of the population grouped by country and city.

Something like.

Country A | Barrie  | `running total for Barrie`
Country A | Barrie2 | `running total for Barrie2`
          |         | `total for Country A`
Country D | Essex   | `running total for Essex`
          |         | `total for Country D`
          |         | `total for everything`

I couldn’t find an extension (I say extension because I plan on using a rollup several times) anywhere so I figure I’d give it a shot. So I started with this simple query.

var groupedElements = elements
    .GroupBy(x => new { x.Country, x.City })
    .Select(x => new { Country = x.Key, City = x.Select(xx => xx.City), Population = x.Sum(xx => xx.Population) })
    .ToList();

This query works as expected so I think I’m on the right track. Next I think I have to figure out which property from groupedElements is aggregate because that’s what we’ll be doing a rollup on. How do I accomplish that? Or perhaps I could have a parameter that makes me specify what column I wish to do the aggregate function on.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T21:32:15+00:00Added an answer on May 17, 2026 at 9:32 pm

    I don’t think this is as easy to do as you might think. Firstly, the items of the result sequence you want are not ‘naturally’ of the same type. You want a running total within each country, grouped totals for each country, and then an overall total.

    Even if you could write a terse query to create this information, the caller would have to differentiate between each kind of total from the result. I wonder if it is even makes much sense to view the result that you want as a single IEnumerable<XXX> in the first place; it might make much more sense to create a nice OO solution like this and proceed from there:

    public interface IGeographicEnity
    {
       string Name { get; }
       int Population { get; }
    }
    
    public class City : IGeographicEntity {...}
    
    public class Country : IGeographicEntity
    {
       public IList<City> Cities { get {...} }       
       public int Population { get { return Cities.Sum(c => c.Population); } }
       ...
    }
    
    public class World : IGeographicEntity
    {
        public IList<Country> Countries { get {...} }       
        public int Population { get { return Countries.Sum(c => c.Population); }
        ...
    }
    

    If you still want to stick with your original idea, here’s the best I can come up with:

    public class PopulationTotal
    {
        // You can use subclassing instead of an enum to represent this
        public enum Kind
        { RunningTotalWithinCountry, TotalForCountry, TotalOverall }
    
        public string GroupName { get; private set; }
        public int Value { get; private set; }
        public Kind Kind { get; private set; }
    
        public static IEnumerable<PopulationTotal> GetTotals(IEnumerable<Element> elements)
        {
            int overallTotal = 0;
    
            foreach (var elementsByCountry in elements.GroupBy(e => e.Country))
            {
                int runningTotalForCountry = 0;
    
                foreach (var element in elementsByCountry)
                {
                    runningTotalForCountry += element.Population;
                    yield return new PopulationTotal
                                        {
                                            GroupName = element.City,
                                            Kind = Kind.RunningTotalWithinCountry,
                                            Value = runningTotalForCountry
                                        };
                }
    
                overallTotal += runningTotalForCountry;
    
                yield return new PopulationTotal
                                    {
                                        GroupName = elementsByCountry.Key,
                                        Kind = Kind.TotalForCountry,
                                        Value = runningTotalForCountry
                                    };
            }
    
            yield return new PopulationTotal
                                {
                                    GroupName = null,
                                    Kind = Kind.TotalOverall,
                                    Value = overallTotal
                                };
        }
    }
    

    Usage:

    var totals = PopulationTotal.GetTotals(elements);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a generic list... public List<ApprovalEventDto> ApprovalEvents The ApprovalEventDto has public class ApprovalEventDto
Today I discovered something that makes me sad: objects of type System.Generic.Collections.List don't have
I have a generic list of objects in C#, for example sake, here's what
I have a DataGridView with its datasource set to a generic list of custom
I have a generic list of objects in C#, and wish to clone the
I'm a newbie when it comes to LINQ... I have an IEnumerable generic list
Anyone have a quick method for de-duplicating a generic List in C#?
I have a method to return a group of objects as a generic list
I have a combobox on my form that is bound to a generic list
I'm trying to build my first generic list and have run into some problems.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.