Reputation: 1005
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.
Upvotes: 4
Views: 3711
Reputation: 317
You can use group be feature of Linq. I'm adding a sample, the output will be.
Group group3 has 1 elements
List<GroupTemp> list = new List<GroupTemp>();
list.Add(new GroupTemp("group1", "1"));
list.Add(new GroupTemp("group1", "2"));
list.Add(new GroupTemp("group2", "3"));
list.Add(new GroupTemp("group2", "4"));
list.Add(new GroupTemp("group3", "5"));
var groupedList = list.GroupBy(t => t.key).ToList();
foreach (var entity in groupedList)
{
Console.WriteLine(String.Format("Group {0} has {1} elements", entity.Key, entity.Count()));
}
Upvotes: 0
Reputation: 16714
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();
Upvotes: 4
Reputation: 1317
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);
Upvotes: 3