Accepted answer

It sounds like you really just want to build up a Lookup from country to servers:

var lookup = servers.ToLookup(server => server.Country);

If that's not what you're looking for, please let me know how it doesn't do what you want :)

Admittedly there's no guarantee that each Country will have all the servers in the original list, and that sounds like it's that distinction which is really the problem.

If your Server already has the Country set, can you not assume that the data is already consistent? If not, shouldn't your Server really have a CID instead of a Country reference? Having a property which will sometimes be consistent with "this" object and sometimes not (i.e. whether server.Country.Contains(server) is guaranteed to return true or not) is ugly IMO.

EDIT: Okay, a possibly nicer alternative is:

var query = servers.GroupBy(server => server.Country.CID);
                   .Select(g => new Country { CID = g.Key,
                                              Servers = g.ToList() });

This is almost the same as fermaref's approach, but I'm explicitly using Country.CID to avoid two servers with equivalent countries not ending up in the same bucket due to potentially odd equality rules.


Now I have a list of servers with each country set and want to group by country so I can set the opposite list.

Linq is for querying and it has a functional mindset where you generate new instances instead of modifying existing instances.

If you want to modify instances, a foreach loop is superior:

List<Server> servers = GetServers();

foreach(Server server in servers)
  Country c = server.Country;

If you must use Linq:

List<Server> servers = GetServers();

foreach(IGrouping<Country, Server> g in servers.GroupBy(s => s.Country))
  Country c = g.Key;
  c.Servers = g.ToList();

Now I just need to invert the list.

ILookup<Country, Server> lookup = servers.ToLookup(s => s.Country);
List<Country> countries = lookup.Select(g => g.Key).ToList();
foreach(Country c in countries)
  c.Servers = lookup[c].ToList();
return countries;


If you can't guarantee that the Country object in each Server object already contains all the Servers, you can create a new Country object:

var groupBy = list.GroupBy(
                    x => x.Country, 
                    x => x, (c, s) => 
                                new Country 
                                  CID = c.CID, 
                                  Servers =  s.ToList()});

However, I'm not sure if that's what you want.

If you can guarantee that the Country object will always contain all Servers, you can could use the following:

var countries = list.SelectMany(s => s.Country).Distinct();

or, if your Country doesn't implement IEquateable:

var groupBy = list.GroupBy(x => x.Country).Select(x => x.Key);

Related Articles