parliament
parliament

Reputation: 22954

Projection: filling 2 arrays at once

I thought I would be clever and write something like this code sample. It also seemed like a clean and efficient way to fill an array without enumerating a second time.

int i = 0;
var tickers = new List<string>();
var resultTable = results.Select(result => new Company
{
      Ticker = tickers[i++] = result.CompanyTicker,
});

I don't really care for an alternative way to do this, because I can obviously accomplish this easily with a for loop. I'm more interested why this snippet doesn't work ie, tickers.Count = 0 after the code runs, despite there being 100+ results. Can anyone tell me why I'm getting this unexpected behavior?

Upvotes: 2

Views: 114

Answers (3)

Dustin Kingen
Dustin Kingen

Reputation: 21265

Linq should ideally not have side affects.

I don't see what would prevent this from being a two step process:

var tickers = results.Select(r => r.CompanyTicker).ToList();

var resultTable = tickers.Select(t => new Company { Ticker = t }).ToList();

Upvotes: 1

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22814

This is due to LINQ's lazy execution. When the query gets executed (i.e. when you iterate over it), the list should have your results. An easy way to do this is to use ToArrayorToList.

Upvotes: 2

Habib
Habib

Reputation: 223332

You need to iterate your query, for example use .ToArray() or ToList() at the end. Currently you just created a query, it hasn't been executed yet.

You may see: LINQ and Deferred Execution

Plus, I believe your code should throw an exception, for IndexOutOfRange, since your List doesn't have any items.

Upvotes: 8

Related Questions