Reputation: 2424
I know that is good practice use LINQ instead of iterative loops, can I modify this code to use LINQ?
List<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?
Upvotes: 5
Views: 185
Reputation: 100288
IEnumerable<PriorElemSt> priorsElemLst = priorsLstIDs.Select((s,i) => new PriorElemSt(s, priorsLstDates[i]));
return filterStudyPriors(priorsElemLst);
Upvotes: 8
Reputation: 46585
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.
Upvotes: 4
Reputation: 21664
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();
Upvotes: 4
Reputation: 26737
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?
Upvotes: 2