Home Access object from outer select clause in LINQ statement
Reply: 3

Access object from outer select clause in LINQ statement

Denis
1#
Denis Published in 2017-12-07 18:37:24Z

Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });

Essentially I am trying to replace the following foreach nested loop:

var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;
Ed Plunkett
2#
Ed Plunkett Reply to 2017-12-07 18:57:10Z

Just use the SelectMany select the final objects. r is already in scope in that lambda, no need to get clever. And you don't need to select p => p; p was already p.

var results =
    positionsToOptimize
    .SelectMany(r =>
        r.Positions.Select(pos => new OptimizedPosition()
        {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            Portfolio = r.Portfolio
        }
    ));
S.Akbari
3#
S.Akbari Reply to 2017-12-07 19:30:33Z

You can select an anonymous type. Something like this:

positionsToOptimize
.Select(p => p)
.SelectMany(r => r.Positions.Select(c => new { temp = r, Positions = c }))
.Select(pos => new OptimizedPosition() 
{
    CalculationType = TCalculationType.Absolute,
    Position = pos.Positions.NetPositionAmount,
    SecurityID = pos.Positions.SecurityID,
    Portfolio = temp.Portfolio       
});
Maxim Kosov
4#
Maxim Kosov Reply to 2017-12-07 20:06:34Z

For cases when you need to use SelectMany and Select in the same query I would suggest to use linq syntax:

from r in positionsToOptimize
from pos in r.Positions
select new OptimizedPosition
{
    CalculationType = TCalculationType.Absolute,
    Position = pos.NetPositionAmount,
    SecurityID = pos.SecurityID,
    Portfolio = r.Portfolio
};

As you can see it is very clean and easy to read and doesn't require any additional temporary objects.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.341171 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO