How can I switch that code to use LINQ
I know that is good practice use LINQ instead of iterative loops, can I modify this code to use LINQ?
List开发者_StackOverflow<string> priorsLstIDs = ServiceUtil.extractColumnValuesAsStringVals(tqrPriors,Helper.STUDY_ID);
List<DateTime> priorsLstDates = ServiceUtil.extractColumnValuesAsDateTimeVals(tqrPriors, "STUDY_DATE");
List<PriorElemSt> priorsElemLst = new List<PriorElemSt>(priorsLstIDs.Count);
PriorElemSt elem;
for (int i = 0; i < priorsLstIDs.Count; i++)
{
elem = new PriorElemSt(priorsLstIDs[i], priorsLstDates[i]);
priorsElemLst.Add(elem);
}
return filterStudyPriors(priorsElemLst);
Thanks.
Update: can the call to filterStudyPriors()
method can be part of the LINQ?
IEnumerable<PriorElemSt> priorsElemLst = priorsLstIDs.Select((s,i) => new PriorElemSt(s, priorsLstDates[i]));
return filterStudyPriors(priorsElemLst);
You could use the Enumerable.Range method like so:
//first get the range of indexes
var range = Enumerable.Range(0, priorsLstIDs.Count);
//now project a list of elements at each index
var priorsElemLst = range.Select(i => new PriorElemSt(priorsLstIDs[i], priorsLstDates[i])).ToList();
You can use the Zip method
var priorsElemLst = priorsLstIDs.Zip(
priorsLstDates, (i, d) => new PriorElemSt(i, d))
In the above statement i
is the item from priorsLstIds and d
the item from priorsLstDates. They will be 'zipped' together using their positions in their lists.
it is not a best practice at all but only if you think it will improve the readability against a performance loss.
LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc.
Is a LINQ statement faster than a 'foreach' loop?
精彩评论