linq - How can I modify this C# code so that Visual Studio recognizes that I'm not an idiot? -
i have 3 lines go
int selectedorgid; foreach (organization o in pd.orgs) if (o.orgname == selectedorgname) selectedorgid = o.orgid; pd.cats.insertonsubmit(new category { orgid = selectedorgid, catname = newcatname }); the middle line, loop, guaranteed, in context of program, set value selectedorgid. however, visual studio flagging last line because
use of unassigned local variable 'selectedorgid'
what way solve other
int selectedorgid = 69; foreach (organization o in pd.orgs) if (o.orgname == selectedorgname) selectedorgid = o.orgid; pd.cats.insertonsubmit(new category { orgid = selectedorgid, catname = newcatname }); ????
although works, seems inelegant solution, since involves magic number. want know proper c# style of solving this.
edit:
looking @ of discussion here, should've specified there such orgid in database. foreach statement should've been written like
foreach (organization o in pd.orgs) { if (o.orgname == selectedorgname) { selectedorgid = o.orgid; break; } } thanks showing me ways better whole thing!
it appears you're iterating through collection, trying find single matching value based on organization name. can use linq's singleordefault() find (at most) 1 match:
var selectedorg = pd.orgs.singleordefault(o => o.orgname == selectedorgname); then call insertonsubmit() if value found: (otherwise, selectedorg null)
if (selectedorg != null) pd.cats.insertonsubmit(new category { orgid = selectedorg.orgid, catname = newcatname });
Comments
Post a Comment