Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list in multiple lists per value of a certain property

Tags:

c#

list

linq

I have a list of data structures that have a property called group. Now, I would like to split this list in multiple lists per group-value. For example, I have 5 objects in the original list with the following group-values:

0. group: "group1"
1. group: "group1"
2. group: "group2"
3. group: "group2"
4. group: "group3"

Keeping that list in mind I would like 3 lists coming out of this per group-value. One list will only have objects with group "group1", the next one "group2" and so on...

I guess I can do this with Linq (I can do this to get a single list from a group with a given value) but I can't figure out how to do it automatically with all possible groups.

like image 303
Dries Avatar asked Sep 05 '25 03:09

Dries


2 Answers

GroupBy does what you are looking for. But if you want the results in a list containing one list per group, you should use it like this:

IList<List<Item>> groups = items.GroupBy(x => x.Group).Select(x => x.ToList()).ToList();
like image 174
Diego Avatar answered Sep 08 '25 01:09

Diego


Assuming you have multiple types in the same collection, I think you should introduce an interface (name is up for debate ;))

public interface IHaveGroup 
{
    string Group { get; }
}

Then, you can just use LINQ.

IEnumerable<IHaveGroup> items = // get all items as a single group
var groups = items.GroupBy(x => x.Group);
like image 45
mstaessen Avatar answered Sep 08 '25 00:09

mstaessen