c# - LINQ Cannot assign void to Implicitly Typed variable -
i trying convert set of data object of linq getting error :
cannot assign void implicitly typed variable
i can understand have make use of select()
function not able figure out how it.
data set:
[zip] [fips] [county] [stateabbr] [statename] 90210 12345 county1 ca california 90210 12346 county2 ca california 90210 12347 county3 ca california 90210 12348 county4 ca california
code snippet:
var zipinfo = results.foreach(z => new zipinfoentity{ zip = z.zip, statename = z.statename, stateabbr = z.stateabbr, fipscountyinfo = new list<fipscountyinfoentity>{ new fipscountyinfoentity { fips = z.fips, county = z.county } } }); public zipinfoentity { public string zip {get;set;} public string statename {get;set;} public string stateabbr {get;set;} public ilist<fipscountyinfoentity> fipscountyinfo {get;set;} } public fipscountyinfoentity { public string fips {get;set;} public string county {get;set;} }
what trying achieve object of zipinfoentity. if see dataset, has zip, stateabbr , statename same rows. county , fips changing.
so final object should like
{ zip: "90210", stateabbr: "ca", statename: "california", fipscountyinfo: [ {fips: "12345", county: "county1"}, {fips: "12346", county: "county2"}, ...] }
first of all, foreach
returns void
, you're trying assign variable cannot in c#.
so begin should have :
var zipinfo = results.select(z => new zipinfoentity{ zip = z.zip, statename = z.statename, stateabbr = z.stateabbr,
and here try assign object of type fipscountyinfoentity
collection of fipscountyinfoentity
( ilist<fipscountyinfoentity>
). , should instead assign new collection :
fipscountyinfo = new list<fipscountyinfoentity>(new fipscountyinfo[] { new fipscountyinfoentity{ fips = z.fips, county = z.county } } });
or change property of type fipscountyinfoentity
, use did :
fipscountyinfo = new fipscountyinfoentity{ fips = z.fips, county = z.county } });
edit :
specified in comment, retrieve 1 element can use firstordefault()
linq method @ end eg. :
var zipinfo = results.select(z => new zipinfoentity{ // ... same code above }).firstordefault();
or :
var zipinfo = results.firstordefault(z => new zipinfoentity{ // ... same code above return true; // needs return true on object want return });
edit2 :
1 element collection of fipscountyinfoentity
suggest doing such :
var zipinfo = results.select(e => new zipinfoentity { zip = z.zip, statename = z.statename, stateabbr = z.stateabbr, fipscountyinfo = results.select(z => new fipscountyinfoentity { fips = z.fips, county = z.county } }).firstordefault();
or using groupby
:
var zipinfo = results.groupby(e => new { e.zip, e.statename, e.stateabbr }).select(e => new zipinfoentity { zip = e.key.zip, statename = e.key.statename, stateabbr = e.key.stateabbr, fipscountyinfo = e.select(c => new fipscountyinfoentity { fips = c.fips, county = c.county }).tolist() });
Comments
Post a Comment