c# - GroupBy - is this expected behavior? -


i have simple eav'ish scenario user can in multiple usergroup , usergroup can have multiple field. select user, select usergroups , show fields.

problem want not show fields duplicate key property.

current situation

fields = user.usergroups     .selectmany(x => x.usergroupfields)     .select(field => new     {         field.key     }) 

product

"fields": [   {     "key": "field 1"   },   {     "key": "field 1"   },   {     "key": "field 2"   } ] 

as can see have multiple field 1, want remove duplicates based on key property. tried groupby() doing weird.

groupby()

fields = user.usergroups     .selectmany(x => x.usergroupfields)     .groupby(field => field.key)     .firstordefault()     .select(field => new     {         field.key     }) 

results in

"fields": [   {     "key": "field 1"   },   {     "key": "field 1"   } ] 

it seems groupby() doing complete opposite of want achieve.

fields = user.usergroups              .selectmany(x => x.usergroupfields)              .groupby(field => field.key)              .select(g=>g.first()); 

groupby has overload taking 2 arguments can applied in case:

fields = user.usergroups              .selectmany(x => x.usergroupfields)              .groupby(field=>field.key, (key, g)=>g.first()); 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -