.net - LINQ GroupBy, convert a one-to-one list to a one-to-many -


this can done in million ways ...

problem. have list of servers belongs country.

countries have many servers, 2 way navigation( think called )

now have list of servers there country set , want group country can opposite list.

list of countries there servers attached icollection of country ( servers )

var groupby = list.groupby(x => x.country, x => x, (c, s) => new {c, s}); foreach (var country in groupby) { } 

this give me result want, have 2 anon types. c country , s list of servers.

how can attach list of servers country object's collection.

classes 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 1 create new country information , put list of servers in constructor ... that's kind of overkill think.

well ... odd simple i'm lost here.

update

i need select servers satisfy condition. that's why have list of servers country. need invert list. can done other way around ?

i'm using repository pattern ef 4 code first. irepository have following methods available option eager load property: single, singleordefault, find , findall

there no lazy load, return icollection or single t.

it sounds want build lookup country servers:

var lookup = servers.tolookup(server => server.country); 

if that's not you're looking for, please let me know how doesn't want :)

admittedly there's no guarantee each country have servers in original list, , sounds it's distinction problem.

if server has country set, can not assume data consistent? if not, shouldn't server really have cid instead of country reference? having property sometimes consistent "this" object , not (i.e. whether server.country.contains(server) guaranteed return true or not) ugly imo.

edit: okay, possibly nicer alternative is:

var query = servers.groupby(server => server.country.cid);                    .select(g => new country { cid = g.key,                                               servers = g.tolist() }); 

this same fermaref's approach, i'm explicitly using country.cid avoid 2 servers equivalent countries not ending in same bucket due potentially odd equality rules.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -