5

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?

Delashmate
  • 2,344
  • 5
  • 26
  • 40

4 Answers4

8
IEnumerable<PriorElemSt> priorsElemLst = priorsLstIDs.Select((s,i) => new PriorElemSt(s, priorsLstDates[i]));
return filterStudyPriors(priorsElemLst);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
4

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.

Ray
  • 45,695
  • 27
  • 126
  • 169
4

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();
Doctor Jones
  • 21,196
  • 13
  • 77
  • 99
2

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?

Community
  • 1
  • 1
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70