Wednesday 15 April 2015

c# - using var, accessising contents outside scope, possible "cast by example??" -



c# - using var, accessising contents outside scope, possible "cast by example??" -

i using linq within if statement. defining var since there few columns of different types. problem after if statement, want foreach since var result defined within if statement, not accessible outside.

after researching problem found online used "cast example" solve this. can't seem understand how works, nor how adjust actual example.

here cast illustration code:

static ienumerable<t> sequencebyexample<t>(t t) { homecoming null; }

below main if statement have different linq query's inside:

if ((currentobject.currentaccount == "") && (currentobject.currentsector == "all")) { var result = row in datatablemastera.asenumerable() grouping row new { symbol = row.field<string>("bloombergsymbol"), desc = row.field<string>("description") } grp select new { symbol = (string)grp.key.symbol, desc = (string)grp.key.desc, delta = grp.where(x => x.field<string>("td_indicator") == "p").select(r => r.field<decimal>("delta")).firstordefault(), prevqty = grp.where(x => x.field<string>("td_indicator") == "p").sum(r => r.field<int64>("qty_net")), prevpl = grp.where(x => x.field<string>("td_indicator") == "p").sum(r => r.field<double>("pl_usd")), topqty = grp.where(x => x.field<string>("td_indicator") == "t").sum(r => r.field<int64>("qty_net")), toppl = grp.where(x => x.field<string>("td_indicator") == "t").sum(r => r.field<double>("pl_usd")) }; createdatagridbreakdownpartb(result.toarray()); } //portfolio-single sector else if ((currentobject.currentaccount == "") && (currentobject.currentsector != "all")) { } //single account-all sectors else if ((currentobject.currentaccount != "") && (currentobject.currentsector == "all")) { } //single account-single sector else if ((currentobject.currentaccount != "") && (currentobject.currentsector != "all")) { } else { messagebox.show("error in createdatagridbreakdown"); } #endregion //foreach (var x in result) //{ //}

can please assist me in issue? much appreciated!

i recommend create class hold data, this:

public class myclass{ public string symbol { get; set; } public string description { get; set; } }

then before if statements, define list of results:

list<myclass> results;

then in each if statement can select this:

results = (from row in datatablemastera.asenumerable() grouping row new { symbol = row.field<string>("bloombergsymbol"), desc = row.field<string>("description") } grp select new myclass() { symbol = (string)grp.key.symbol, description = (string)grp.key.desc, //etc... }).tolist();

the foreach should ok...

foreach (myclass x in results) { string symbol = x.symbol; }

c# linq

No comments:

Post a Comment