Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I switch that code to use LINQ

Tags:

c#

.net

linq

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?

like image 533
Delashmate Avatar asked Sep 20 '11 13:09

Delashmate


People also ask

Is LINQ only for C#?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.

When should you use LINQ in your program?

Readable code: LINQ makes the code more readable so other developers can easily understand and maintain it. Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time.

What can I use instead of foreach in C#?

Why: You prefer to use LINQ syntax rather than a foreach loop. LINQ makes a query into a first-class language construct in C#. LINQ can reduce the amount of code in a file, make the code easier to read, and allow different data sources to have similar query expression patterns.

Can we use LINQ in .NET core?

NET Core LINQ stands for Language Integrated Query. Language Integrated Query is one structured query that is used to retrieve data from the database and other different sources and formats. LINQ tutorials will assist you to find out the LINQ language using topics that go from basic to advanced.


2 Answers

IEnumerable<PriorElemSt> priorsElemLst = priorsLstIDs.Select((s,i) => new PriorElemSt(s, priorsLstDates[i]));
return filterStudyPriors(priorsElemLst);
like image 93
abatishchev Avatar answered Sep 25 '22 18:09

abatishchev


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();
like image 31
Doctor Jones Avatar answered Sep 21 '22 18:09

Doctor Jones