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.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With