Suppose I have three users and I want to group them by their country. I would do this:
var users = new[]
{
new User { Name = "Phil", Country = "UK" },
new User { Name = "John", Country = "UK" },
new User { Name = "Mike", Country = "USA" }
};
List<IGrouping<string, User>> groupedUsers
= users.GroupBy(user => user.Country).ToList();
Now suppose my program gets three more users later on, so I group them too:
var moreUsers = new[]
{
new User { Name = "Phoebe", Country = "AUS" },
new User { Name = "Joan", Country = "UK" },
new User { Name = "Mindy", Country = "USA" }
};
List<IGrouping<string, User>> moreGroupedUsers
= moreUsers.GroupBy(user => user.Country).ToList();
I now have two seperate groupings, groupedUsers
and moreGroupedUsers
. How can I merge them into one whilst keeping the grouping valid?
Since the IGrouping<,>
API does not provide a mutating interface, you would need to either:
Dictionary<string, List<User>>
to which you can addThe first sounds simpler. It could be either:
var groupedUsers = groupedUsers.SelectMany(grp => grp)
.Concat(moreUsers)
.GroupBy(x => x.Country).ToList();
or:
var groupedUsers = users.Concat(moreUsers)
.GroupBy(x => x.Country).ToList();
(if you still have users
available)
The latter could be done with:
var mutable = users.GroupBy(user => user.Country).ToDictionary(
grp => grp.Key, grp => grp.ToList());
then (to append):
foreach(var user in moreUsers) {
List<User> list;
if(!mutable.TryGetValue(user.Country, out list)) {
mutable.Add(user.Country, list = new List<User>());
}
list.Add(user);
}
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