Skip to content
Fix Code Error

Group by in LINQ

March 13, 2021 by Code Error
Posted By: Anonymous

Let’s suppose if we have a class like:

class Person { 
    internal int PersonID; 
    internal string car; 
}

I have a list of this class: List<Person> persons;

And this list can have multiple instances with same PersonIDs, for example:

persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 

Is there a way I can group by PersonID and get the list of all the cars he has?

For example, the expected result would be

class Result { 
   int PersonID;
   List<string> cars; 
}

So after grouping, I would get:

results[0].PersonID = 1; 
List<string> cars = results[0].cars; 

result[1].PersonID = 2; 
List<string> cars = result[1].cars;

From what I have done so far:

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key, // this is where I am not sure what to do

Could someone please point me in the right direction?

Solution

Absolutely – you basically want:

var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.ToList() };

Or as a non-query expression:

var results = persons.GroupBy(
    p => p.PersonId, 
    p => p.car,
    (key, g) => new { PersonId = key, Cars = g.ToList() });

Basically the contents of the group (when viewed as an IEnumerable<T>) is a sequence of whatever values were in the projection (p.car in this case) present for the given key.

For more on how GroupBy works, see my Edulinq post on the topic.

(I’ve renamed PersonID to PersonId in the above, to follow .NET naming conventions.)

Alternatively, you could use a Lookup:

var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);

You can then get the cars for each person very easily:

// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];
Answered By: Anonymous

Related Articles

  • grouping and summarizing to find mean and median…
  • SQL query return data from multiple tables
  • Vue - Deep watch change of array of objects, either…
  • Is there a function in python that can easily plot…
  • Getting infinite loop after entering 2 objects to…
  • Eclipse will not start and I haven't changed anything
  • Gradle error: Execution failed for task…
  • Python regex expression between variable strings and…
  • How delete an item using vuex?
  • Vue.js - emit to update array not working
  • How to Deserialize XML document
  • Jetpack Compose and Hilt Conflict
  • org.gradle.api.tasks.TaskExecutionException:…
  • Pushing an object to an array using a repository
  • How to get a value inside an ArrayList java
  • Callback functions in C++
  • Backbone.js - How to create a collection that has…
  • SQL SUM and divide linked tables
  • Unable to create a constant value of type Only…
  • How do I make a JSON object with multiple arrays?
  • Room @Relation with two foreign keys
  • Get column value length, not column max length of value
  • Is it okay to delete attributes in my…
  • How to pass an array within a query string?
  • Execution failed for task…
  • show and hide divs based on radio button click
  • unable to change text size
  • How to find length of a string array?
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • RESTful URL design for search
  • Backbone.js Uncaught TypeError this.model.each is…
  • Fastest way to iterate over all the chars in a String
  • how create a simple object animation in processing
  • Using templates as select option name in Aurelia
  • sorting an array by using pointer arithmetic
  • Adding gif image in an ImageView in android
  • Create multiple donut plots in one plot
  • Svelte Each function in Nested Json
  • Entity Framework LINQ complex query - combine…
  • Continuously adding to a dictionary
  • How to group an array of objects by key
  • Eclipse fails to open .vue files in Web Page Editor
  • What is a NullReferenceException, and how do I fix it?
  • SQLException: No suitable Driver Found for…
  • Why won't ".includes" work with my two dimensional array?
  • How do I include certain conditions in SQL Count
  • VueJS : Filter array of objects when user search for…
  • Problems Installing CRA & NextJS from NPM…
  • How to filter a RecyclerView with a SearchView
  • How to group data from attributes using for loops in VueJS
  • Filter Rank Based On Column Not being Ordered By
  • Gradle: Execution failed for task ':processDebugManifest'
  • What's the best way to get the last element of an…
  • Set the local state using useEffect on Redux prop change
  • postgressql/typeorm - Count with filter on same…
  • Can't access Eclipse marketplace
  • REST API - why use PUT DELETE POST GET?
  • Polymer static variable listener?
  • Android- Error:Execution failed for task…
  • problem with client server unix domain stream…
  • Ember Store: Sort, Filter, Find Records
  • jQuery add blank option to top of list and make…
  • vuejs v-for only few elements from array, based on…
  • What is The Rule of Three?
  • How to convert a ruby hash object to JSON?
  • VueJS 2.0 v-model dynamic target inside v-for
  • Query an object array using linq
  • XML Serialize generic list of serializable objects
  • Vue.js $remove not removing element after deleted…
  • android studio 0.4.2: Gradle project sync failed error
  • Undefined reference to 'vtable for ✘✘✘'
  • Knight's tour Problem - storing the valid moves then…
  • Distinct by property of class with LINQ
  • Joining Spark dataframes on the key
  • Core Data: Quickest way to delete all instances of an entity
  • Bootstrap 3 Aspect ratio on image
  • Add multiple items to a list
  • receiving json and deserializing as List of object…
  • SQL Server IF NOT EXISTS Usage?
  • Smart way to truncate long strings
  • Dynamically assign to string key typescript error No…
  • Polymer 3 Element - NotSupportedError
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Compiler error: "class, interface, or enum expected"
  • C++ error: expected class member or base class name…
  • C++ OpenGL stb_image.h errors
  • Accessing a Shared File (UNC) From a Remote,…
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Repeating a function when someone reacts to it
  • What are forward declarations in C++?
  • What's the correct way to pass props as initial data…
  • Baffling variadic templates exercise
  • Dependent/Cascading Dropdowns in Aurelia
  • Searching for element in array in aurelia view
  • Putting images with options in a dropdown list
  • Backbone collection: Retrieve distinct values of a…
  • Ruby class instance variable vs. class variable
  • Initialize Array of Objects using NSArray
  • Java - atore values in multidimensional array from…
  • What are the undocumented features and limitations…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

List all environment variables from the command line

Next Post:

jQuery.click() vs onClick

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error