Compartir a través de


Using LINQ to Objects to simplify procedural code

How many times haven't you written procedural code to loop through lists to do sorting and filtering of items like this?

List<Position> positions = GetPositions();

// Sort the list and filter

SortedList<string, Position> openPositions = new SortedList<string,Position>();

foreach (Position position in positions)

{

    if (position.Quantity > 0.0)

        openPositions.Add(position.Paper, position); 

}

The above sample is of course very simple, but by using LINQ to Objects you are able to do it even simpler like this:

List

<Position> positions = GetPositions();
var openPositions = from p in positions where p.Quantity > 0.0 orderby p.Paper select p;

That was nice! I find that using LINQ to Objects makes my code more clean and even easier to read and understand.