I have this code:
#if (loaded && weathers != null && weathers.Count() > 0 && !weathersLoading && options != null)
{
<ApexChart TItem="object"
Title="Temperature Chart"
Options=#options XAxisType="XAxisType.Category" Debug>
<ApexPointSeries TItem="Data.Entities.Weather"
Items="weathers.Where(w => w.HighTemp != null)"
Name="High Temp"
SeriesType="SeriesType.Bar"
XValue="#(e => e.DateP)"
YValue="#(e => (decimal?)e.HighTemp)"
OrderBy="e => e.X" />
<ApexPointSeries TItem="Data.Entities.Weather"
Items="weathers.Where(w => w.LowTemp != null)"
Name="Low Temp"
SeriesType="SeriesType.Bar"
XValue="#(e => e.DateP)"
YValue="#(e => (decimal?)e.LowTemp)"
OrderBy="e => e.X" />
#if (averages != null && averages.Count() > 0)
{
List<AvgHigh> avsH = averages.Select(g => new AvgHigh()
{
Date = weathers.First(lw => lw.Date.DayOfYear == g.Key).Date,
AvgHighTemp = g.Average(w => w.HighTemp) ?? 0,
DateP = Business.Home.GregorianToP2(
weathers.First(lw => lw.Date.DayOfYear == g.Key).Date).Substring(2)
}).ToList();
List<AvgLow> avsL = averages.Select(g => new AvgLow()
{
Date = weathers.First(lw => lw.Date.DayOfYear == g.Key).Date,
AvgLowTemp = g.Average(w => w.LowTemp) ?? 0,
DateP = Business.Home.GregorianToP2(
weathers.First(lw => lw.Date.DayOfYear == g.Key).Date).Substring(2)
}).ToList();
<ApexPointSeries TItem="AvgHigh"
Items="#avsH"
Name="Avg High"
SeriesType="SeriesType.Line"
XValue="#(e => e.DateP)"
YValue="#(e => (decimal?)e.AvgHighTemp)"
OrderBy="e=>e.X" />
<ApexPointSeries TItem="AvgLow"
Items="#avsL"
Name="Avg Low"
SeriesType="SeriesType.Line"
XValue="#(e => e.DateP)"
YValue="#(e => (decimal?)e.AvgLowTemp)"
OrderBy="e=>e.X" />
}
</ApexChart>
#code {
private ApexChartOptions<object> options = new ApexChartOptions<object>
{
Chart = new Chart
{
Stacked = true
},
PlotOptions = new PlotOptions
{
Bar = new PlotOptionsBar
{
Horizontal = false
}
},
Colors = new List<string> { "#ffa500", "#4169e1", "#ff0000", "#ffffff" }
};
}
While I debug and verify that all collections have values, But I get this error:
object reference not set to an instance of an object. at apexcharts.apexpointseries`1.oninitialized() at microsoft.aspnetcore.components.componentbase.runinitandsetparametersasync()
I am converting a working radzen blazor chart to apex chart because of stacked column chart it has.
In blazor how to correct this?
Related
I have 2 almost identical linq queries and want to remove repeating code from it. The only difference is the extra property in the GroupBy depending on some true/false condition.
How can I conditionally group by in linq without repeating the code like below?
var allergensList = _context.RecipeAllergens
.Where(x => x.ParentId == Id && x.AllergenId != null)
.ToList();
var allergens = new List<AllergenInfo>();
if (isRecipe)
{
allergens = allergensList
.GroupBy(x => new { x.AllergenName, x.AllergenIcon, x.AllergenMaycontains })
.Select(a =>
{
var v = a.OrderBy(x => x.AllergenMaycontains).First();
return new AllergenInfo
{
AllergenName = v.AllergenName,
AllergenIcon = v.AllergenIcon,
AllergenMayContain = v.AllergenMaycontains ?? false
};
})
.ToList();
}
else
{
allergens = allergensList
.GroupBy(x => new { x.AllergenName, x.AllergenIcon })
.Select(a =>
{
var v = a.OrderBy(x => x.AllergenMaycontains).First();
return new AllergenInfo
{
AllergenName = v.AllergenName,
AllergenIcon = v.AllergenIcon,
AllergenMayContain = v.AllergenMaycontains ?? false
};
})
.ToList();
}
You can left grouping by x.AllergenMaycontains but under condition
allergens = allergensList
.GroupBy(x => new { x.AllergenName, x.AllergenIcon, AllergenMaycontains = isRecipe ? x.AllergenMaycontains : false })
.Select(a =>
{
var v = a.OrderBy(x => x.AllergenMaycontains).First();
return new AllergenInfo
{
AllergenName = v.AllergenName,
AllergenIcon = v.AllergenIcon,
AllergenMayContain = v.AllergenMaycontains ?? false
};
})
.ToList();
I have the following code..
var GetStock = db.tabStocks.Where(x => x.SourceDocRef == InvoiceNumber.Text);
List<tabStock> tbs = new List<tabStock>();
foreach (var Stk in GetStock)
{
switch (GetStock.Any(y => y.ProductSKU == Stk.ProductSKU && y.Id != Stk.Id))
{
case true:
if (!(tbs.AsEnumerable().Any(x => x.Id == Stk.Id))) {
tbs.Add(Stk);
}//tbs.AddRange(GetStock2.Where(g => g.ProductSKU == Stk.ProductSKU && g.Id != Stk.Id));
var GetOthers = GetStock.Where(x => x.Id != Stk.Id && x.ProductSKU == Stk.ProductSKU );
foreach (var Gt in GetOthers) {
if (!(tbs.AsEnumerable().Any(x => x.Id == Gt.Id))) {
tbs.Add(Gt);
}
} break;
}
}
//Group and Remove tbs
Literal1.Text += tbs.AsEnumerable().Count();
try
{
var GroupIt = tbs.GroupBy(x => x.ProductSKU ).AsEnumerable()
.Select(g => new tabStock
{
ProductName = g.FirstOrDefault().ProductName,
ProductSKU = g.FirstOrDefault().ProductSKU,
Qty = g.Sum(n => n.Qty).Value,
OutQty = g.Sum(n => n.Qty).Value,
Bal = (db.tabStocks.Any(x => x.ProductSKU == g.FirstOrDefault().ProductSKU && x.SourceDocRef != g.FirstOrDefault().SourceDocRef && x.Id < g.OrderBy(t => t.Id).FirstOrDefault().Id) ? db.tabStocks.Where(x => x.ProductSKU == g.FirstOrDefault().ProductSKU && x.SourceDocRef != g.FirstOrDefault().SourceDocRef && x.Id < g.OrderBy(t => t.Id).FirstOrDefault().Id).OrderByDescending(x => x.Id).FirstOrDefault().Bal - g.Sum(f => f.Qty).Value : (0 - g.Sum(f => f.Qty)).Value).Value,
TransactionRef = g.FirstOrDefault().TransactionRef,
CreatedBy = g.FirstOrDefault().CreatedBy,
CreationDate = g.FirstOrDefault().CreationDate,
SourceDocRef = g.FirstOrDefault().SourceDocRef,
InQty = 0,
transactionType = "Sale",
UnitCost = g.FirstOrDefault().UnitCost.Value,
Received = 0,
TotalValuation = 0,
});
foreach (var NewStk in GroupIt.AsEnumerable())
{
tabStock stk = new tabStock();
stk.ProductName = NewStk.ProductName;
stk.ProductSKU = NewStk.ProductSKU;
stk.Qty = NewStk.Qty;
stk.OutQty = NewStk.OutQty;
stk.Bal = NewStk.Bal;
stk.transactionType = NewStk.transactionType;
stk.TransactionRef = NewStk.TransactionRef;
stk.CreatedBy = NewStk.CreatedBy;
stk.CreationDate = NewStk.CreationDate;
stk.SourceDocRef = NewStk.SourceDocRef;
stk.InQty = NewStk.InQty;
stk.UnitCost = NewStk.UnitCost;
stk.Received = 0;
stk.TotalValuation = 0;
db.tabStocks.Add(stk);
}
foreach (var OldStk in tbs.AsEnumerable())
{
db.tabStocks.Remove(OldStk);
}
db.SaveChanges();
For some reason i have this error:
Unable to create a constant value of type
'Type'. Only primitive types or enumeration types are supported in this context
Can anyone help me point to what this could be. I have looked at a lot of others related, nothing seems to work.. toList(), AsEnumerable(). Where is my code wrong please.
This question is propably more a concept question, but I'm stuck here logically.
I'm using LiveChart for WPF and I try to build a simple CartesianChart dynamically.
I load my Data from a CSV into a List, I'm counting how many times each datapair is in that file and add the amount. The result from this Linq request looks like this:
[0] { Dates = "20191123", Rank = "1st", Amount = 1 } <Anonymous Type>
I go through this result to pick me each date individually for the Lables of my CartesianChart
Now I would like to add my result Data into the CartesianChart for that I need a SeriesCollection mine looks like this:
SeriesCollection = new SeriesCollection
{
new LineSeries
{
Title = "1st",
Values = new ChartValues<int> {}
},
new LineSeries
{
Title = "2nd",
Values = new ChartValues<int> {}
},
new LineSeries
{
Title = "3rd",
Values = new ChartValues<int> {}
}
}
But when I go through my data on some dates I dont have for example first place, so I need a 0 amount value for this day. I'm struggeling to add this to my data.
Here is pretty much the whole code block im experimenting with, that also why it looks a little messy.
var data = File.ReadAllLines(FilePathes.resultPath).ToList();
var rankHistoryList = new List<RankHistory>();
foreach (var line in data)
{
rankHistoryList.Add(RankHistory.parse(line));
};
var result = rankHistoryList.GroupBy(x => new { x.Dates, x.Rank })
.Select(g => new { g.Key.Dates, g.Key.Rank, Amount = g.Count() })
.ToList();
var dates = new List<string>();
foreach (var entry in result)
{
dates.Add(entry.Dates);
}
var singleDates = dates.GroupBy(x => x).Select(grp => grp.First()).ToArray();
foreach (var day in singleDates) {
foreach (var entry in result) {
if (entry.Rank == "1st" && day == entry.Dates)
{
SeriesCollection[0].Values.Add(entry.Amount);
}
else if (entry.Rank != "1st" && day == entry.Dates)
{ SeriesCollection[0].Values.Add(0); }
}
}
I think my answer is the most complicated but at least it works:
var allRanks = new List<string>
{
"1st"
,"2nd"
,"3rd"
};
foreach (var entry in result)
{
dates.Add(entry.Dates);
}
var singleDates = dates.GroupBy(x => x).Select(grp => grp.First()).ToArray();
Labels = singleDates;
foreach (var ran in allRanks)
{
foreach (var day in singleDates)
{
if (ran == "1st")
{
if (result.Exists(x => x.Dates == day && x.Rank == ran) == true)
{
SeriesCollection[0].Values.Add(result.Where(w => w.Dates == day && w.Rank == ran).Select(x => x.Amount).First());
}
else SeriesCollection[0].Values.Add(0);
}
if (ran == "2nd")
{
if (result.Exists(x => x.Dates == day && x.Rank == ran) == true)
{
SeriesCollection[1].Values.Add(result.Where(w => w.Dates == day && w.Rank == ran).Select(x => x.Amount).First());
}
else SeriesCollection[1].Values.Add(0);
}
if (ran == "3rd")
{
if (result.Exists(x => x.Dates == day && x.Rank == ran) == true)
{
SeriesCollection[2].Values.Add(result.Where(w => w.Dates == day && w.Rank == ran).Select(x => x.Amount).First());
}
else SeriesCollection[2].Values.Add(0);
}
}
}
how to simplify below code:
public List<Cwzz_CashFlowItem> AllDataPage(int start, int limit, out int total, string xmbmLike, string xmmcLike)
{
List<Cwzz_CashFlowItem> ll;
if (xmbmLike != "" && xmmcLike != "")
{
total = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.Count(v => v.CashFlowName.Contains(xmmcLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.Where(v => v.CashFlowName.Contains(xmmcLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else if (xmbmLike != "" && xmmcLike == "")
{
total = _ctx.Cwzz_CashFlowItem
.Count(v => v.CashFlowCode.Contains(xmbmLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowCode.Contains(xmbmLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else if (xmbmLike == "" && xmmcLike != "")
{
total = _ctx.Cwzz_CashFlowItem
.Count(v => v.CashFlowName.Contains(xmmcLike));
ll = _ctx.Cwzz_CashFlowItem
.Where(v => v.CashFlowName.Contains(xmmcLike))
.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit).ToList();
}
else
{
total = _ctx.Cwzz_CashFlowItem.Count();
ll = _ctx.Cwzz_CashFlowItem
.OrderBy(v => v.CashFlowCode)
.Skip(start).Take(limit).ToList();
}
return ll;
}
if there are more conditions not two, the if-else will be more complicated, so how to simplify code above.
Linq expressions can be chained. Avoid premature coercion into a List<>.
public IQueryable<Cwzz_CashFlowItem> AllDataPage(...) {
IQueryable<Cwzz_CashFlowItem> ll = _ctx.Cwzz_CashFlowItem;
if (xmbmLike != "")
{
ll = ll.Where(v => v.CashFlowCode.Contains(xmbmLike));
}
if (xmcmLike != "")
{
ll = ll.Where(v => v.CashFlowCode.Contains(xmcmLike));
}
return ll.OrderBy(v => v.CashFlowCode).Skip(start).Take(limit);
}
I'll leave returning the out Count as an exercise.
I'm trying to code a method that, in it's class given the values of some of the attributes, returns a filtered DbSet. The code, so far, is:
public IEnumerable<Pesquisa> Pesquisas {
get {
PrometheusDBContext db = new PrometheusDBContext();
var temp = db.Pesquisas;
if ((this.Filtro.Nome != null) && (this.Filtro.Nome.Trim() != ""))
{
temp = (temp.Where(p => SqlFunctions.PatIndex(this.Filtro.Nome, p.Nome) > 0) as DbSet<Pesquisa>);
}
if ((this.Filtro.CodTipoPesquisa != null) && (this.Filtro.CodTipoPesquisa.Trim() != ""))
{
temp = (temp.Where(p => p.CodTipoPesquisa == this.Filtro.CodTipoPesquisa.Trim()) as DbSet<Pesquisa>);
}
if ((this.Filtro.IDStatusPesquisa != null) && (this.Filtro.IDStatusPesquisa > 0))
{
temp = (temp.Where(p => p.IDStatusPesquisa == this.Filtro.IDStatusPesquisa) as DbSet<Pesquisa>);
}
if ((this.Filtro.DataCriacao_Inicial != null) && (this.Filtro.DataCriacao_Final != null))
{
temp = (temp.Where(p => (p.DataCriacao >= this.Filtro.DataCriacao_Inicial) && (p.DataCriacao <= this.Filtro.DataCriacao_Final)) as DbSet<Pesquisa>);
}
else
{
if (this.Filtro.DataCriacao_Inicial != null)
{
temp = (temp.Where(p => p.DataCriacao >= this.Filtro.DataCriacao_Inicial) as DbSet<Pesquisa>);
}
if (this.Filtro.DataCriacao_Final != null)
{
temp = (temp.Where(p => p.DataCriacao <= this.Filtro.DataCriacao_Final) as DbSet<Pesquisa>);
}
}
return temp
.Include(p => p.Usuario)
.Include(p => p.StatusPesquisa)
.Include(p => p.TipoPesquisa)
.Include(p => p.ModeloTermoAdesao)
.Include(p => p.Pacientes)
.ToList();
}
Problem is: everytime one of the attributes is filled with some value (i.e.: this.Filtro.Nome = "test" ), the ToList() raises an ArgumentNullExcpetion. Any ideas?
You shouldn't cast to DbSet at the end of each line.
Also, declare
IQueryable<Pesquisa> temp = db.Pesuisas;
// your code follows.
The reason behind it is that although you start with a DbSet, applying operators changes its type. Your dynamic cast returns null then.