This can be done in a million ways …
Problem.
I have a list of servers which belongs to a country.
Countries have many servers, so its a 2 way navigation( I think its called )
Now I have a list of servers with there country set and want to group by country so I can get the opposite list.
List of countries with all there servers attached to the ICollection of the Country ( Servers )
var groupBy = list.GroupBy(x => x.Country, x => x, (c, s) => new {c, s});
foreach (var country in groupBy)
{
}
This will almost give me the result I want, but now I have 2 anon types.
C which is country and S which is the list of servers.
How can I attach the list of servers to the country object’s Collection.
Classes look like this… simplified.
public class Server
{
public short SID { get; set; }
public Country Country { get; set; }
}
public class Country
{
public byte CID { get; set; }
public ICollection<Server> Servers { get; set; }
}
I guess one could create a new Country with the information and then also put the list of servers in the constructor … but that’s kind of overkill I think.
Well … this odd to be simple but I’m lost here.
Update
I need to select all servers that satisfy some condition. That’s why I have a list of servers with the country. Now I just need to invert the list. Can this be done the other way around ?
I’m using the Repository Pattern with EF 4 Code First.
IRepository
I only have the following methods available with a option to eager load a property:
Single, SingleOrDefault, Find and FindAll
There are no lazy load, they all return ICollection or a single T.
It sounds like you really just want to build up a Lookup from country to servers:
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
Countrywill have all the servers in the original list, and that sounds like it’s that distinction which is really the problem.If your
Serveralready has theCountryset, can you not assume that the data is already consistent? If not, shouldn’t yourServerreally have a CID instead of aCountryreference? Having a property which will sometimes be consistent with “this” object and sometimes not (i.e. whetherserver.Country.Contains(server)is guaranteed to returntrueor not) is ugly IMO.EDIT: Okay, a possibly nicer alternative is:
This is almost the same as fermaref’s approach, but I’m explicitly using
Country.CIDto avoid two servers with equivalent countries not ending up in the same bucket due to potentially odd equality rules.