Reuse function results in LINQ - performance

I have the following query in LINQ as an example. Is it possible to save the results of the GetCalendarResources function so I wouldn't have to call it more than once? Thanks.
var query = from T in query2.AsEnumerable()
select new Event
{
resource = GetCalendarResources(T.eventID),
text = GetCalendarResources(T.eventID) + T.eventName
};

You can use the let keyword, which gives you the liberty to use its value for the next level:
var query = from T in query2.AsEnumerable()
let res= GetCalendarResources(T.eventID)
select new Event
{
resource =res,
text = res + T.eventName
};

Related

Infer elastic search type from index name in NEST

Is it possible to infer type of elastic search document by index name, since I'm trying to call multiple indices and have to use object type.
var indices = Indices.Index(entities);
var search = new SearchRequest(indices)
{
From = page,
Size = pageSize,
Query = fullQuery,
IgnoreUnavailable = true,
};
var response = this.client.Search<object>(search);
Is it possible to have each object infer type from elastic search, based on some type/indexName mapping?
May be you can try out Generics.
var indices = Indices.Index(entities);
var search = new SearchRequest(indices)
{
From = page,
Size = pageSize,
Query = fullQuery,
IgnoreUnavailable = true,
};
var response = this.client.Search<T>(search);
return response;

Linq dynamic include

Can some one please tell me how to dynamically include child object using linq.
using (var cont = _entities)
{
var query = cont.ParentTable;
if(includechild1)
query.Include("Child1");
if(includechild1)
query.Include("Child2");
return query.ToList();
}
The above code is not including child objects.But the below code does
_entities.ParentTable.Include("Child1").ToList();
Please some one suggest an idea.
Set result of include to variable:
using (var cont = _entities)
{
var query = cont.ParentTable;
if(includechild1)
query = query.Include("Child1");
if(includechild1)
query = query.Include("Child2");
return query.ToList();
}

creating Chart for mvc3 razor using database

I'm new to asp.net mvc3 and been reading to a lot of posts in stackoverflow on Chart for MVC3 razor.
However, i could not create a chart for this. Basically this is my sql query
SELECT COUNT(RequestStatus) AS Expr1, RequestStatus
FROM Request
GROUP BY RequestStatus
So far, in my control view, this is my code:
public ActionResult RequestReport()
{
var result = from p in db.Requests
group p by p.RequestStatus into pgroup
let count = pgroup.Count()
orderby count
select new { Count = count, RequestStatus = pgroup.Key }.ToString();
var x = new [] {result};
Chart chart = new Chart(600, 400)
.AddSeries(yValues: x , yFields:"Count")
.AddTitle("Request Statistic");
this.ViewBag.Chart = chart;
return View();
}
and
in View :
#ViewBag.Chart.Write()
please help me solve this issue. i could not find a simple tutorial for this.
ive made some changes on the code in controller.
using (var db = new ITAMMVCDBEntities())
{
var rs = db.Requests.GroupBy(o=>o.RequestStatus).ToList();
var result = from o in db.Requests
group o by o.RequestStatus
into g
select new
{
result = g.Count()
};
Chart chart = new Chart(600, 400)
.AddSeries(
xValue: rs.Select(x=>x.Key).ToArray() ,
yValues: result.ToArray()
)
.AddTitle("Request Statistic");
this.ViewBag.Chart = chart;
return View();
}
now i get this error msg when run
Series data points do not support values of type <>f__AnonymousType1`1[System.Int32] only values of these types can be used: Double, Decimal, Single, int, long, uint, ulong, String, DateTime, short, ushort.
i think my xValue is okay as it displays by group
but problem populationg yValue which will display the value of each group

how do you loop through all rows in kendoUI grid with filter

here's my code. it works, if you want to loop through all the rows. now, QA told me I have to make it to support filter. so, when user use filter, only a subset of the rows will show on the grid. I need to only loop through only those rows.
var entityGrid = $("#EntitesGrid").data("kendoGrid");
var data = entityGrid.dataSource.data();
var totalNumber = data.length;
for(var i = 0; i<totalNumber; i++) {
var currentDataItem = data[i];
VersionIdArray[i] = currentDataItem.VersionId;
}
I tried.
var data = entityGrid.dataSource.data().fetch();
and
var data = entityGrid.dataSource.data().filter();
couldn't get it working.
For future reference and for those who are interested, I found the the solution at:
http://colinmackay.scot/2012/07/23/kendo-ui-paging-and-accessing-the-filtered-results-in-javascript/
It works by first getting hold of the grid's data source, getting the filter and the data, creating a new query with the data and applying the filter to it. While this does result in getting the results of the filter it does have the distinct disadvantage of processing the filter operation twice.
function displayFilterResults() {
// Gets the data source from the grid.
var dataSource = $("#MyGrid").data("kendoGrid").dataSource;
// Gets the filter from the dataSource
var filters = dataSource.filter();
// Gets the full set of data from the data source
var allData = dataSource.data();
// Applies the filter to the data
var query = new kendo.data.Query(allData);
var filteredData = query.filter(filters).data;
// Output the results
$('#FilterCount').html(filteredData.length);
$('#TotalCount').html(allData.length);
$('#FilterResults').html('');
$.each(filteredData, function(index, item){
$('#FilterResults').append('<li>'+item.Site+' : '+item.Visitors+'</li>')
});
}
Many thanks!!! With this help now I did this...
kendo.data.DataSource.prototype.dataFiltered = function () {
// Gets the filter from the dataSource
var filters = this.filter();
// Gets the full set of data from the data source
var allData = this.data();
// Applies the filter to the data
var query = new kendo.data.Query(allData);
// Returns the filtered data
return query.filter(filters).data;
}
So now I can get my filtered data very easy!!! Awesome!!!
Example:
var dataFiltered = $("#MyGrid").data("kendoGrid").dataSource.dataFiltered();

Integrating custom method into LINQ to Entities query

I have a custom method that performs some calculation on a set of data:
private int GetPercentages(int OriginalValue, int TotalValue)
{
var newValue = (int)Math.Round(((decimal)OriginalValue / (decimal)TotalValue) * 100);
return newValue;
}
I need to be able to run this method inside of a LINQ to Entities query:
var data = from SurveyResponseModel in db.SurveyResponseModels
group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
select new ResultsViewModel()
{
MemberId = resultCount.Key,
PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp),
PatientFollowUpResultPct = GetPercentages(db.SurveyResponseModels.Count(r => r.PatientFollowUp),totalResponsesResult),
ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice),
};
I need to run this on about 20 more lines inside of the query so just sticking it inline doesn't seem like a great option. I understand that it needs to be converted into SQL syntax, but is there anything else like this that I can do?
You need to make a lambda expression that calculates the percentage like this:
Expression<Func<int, int, int>> calcPercentage =
(OriginalValue, TotalValue) => (int)Math.Round(((decimal)OriginalValue / (decimal)TotalValue) * 100);
And use it like this:
var data = from SurveyResponseModel in db.SurveyResponseModels.ToExpandable()
group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
select new ResultsViewModel()
{
MemberId = resultCount.Key,
PatientFollowUpResult = db.SurveyResponseModels.Count(r => r.PatientFollowUp),
PatientFollowUpResultPct = calcPercentage.Invoke(db.SurveyResponseModels.Count(r => r.PatientFollowUp), totalResponsesResult),
ChangeCodingPracticeResult = db.SurveyResponseModels.Count(r => r.ChangeCodingPractice),
};
More info about calling functions in LINQ queries here.

Resources