I am using LinQ inside an if statement. Also defining as var
since there are a few columns of different types. The problem is that after the if statement, I want to do a foreach
but since the var result is defined inside the if statement, it is not accessible outside.
After researching the problem I found online someone used "cast by example" to solve this. But I can't seem to understand how it works, nor how to adjust it to my actual example.
Here is the cast by example code:
static IEnumerable<T> SequenceByExample<T>(T t) { return null; }
Below is the main if statement which I will have different LinQ query's inside:
if ((currentObject.CurrentAccount == "") && (currentObject.CurrentSector == "All"))
{
var result = from row in datatableMasterA.AsEnumerable()
group row by new
{
symbol = row.Field<string>("BloombergSymbol"),
desc = row.Field<string>("Description")
}
into 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 someone please assist me in this issue? Much appreciated!