user1250264
user1250264

Reputation: 905

Can't call another method from LINQ statement

I have a c# statement which iterate thru a collection of row. One of the fields call a private method to get an array of object but I am getting null. I placed a breakpoint inside the linq but it never hits the method.

Here is my code

IQueryable<MyObject> myObject = ds.Tables['Table'].AsEnumerable().Select(row => new MyObject
{
  id = row.Field<int>("ID"),
  MyCollectionArray = this.getCollectionArray(row.Field<string>("MyAggregatedString")),
}).AsQueryable();

private MyObect[] getCollectionArray(string concatString)
{

  // placed a breakpoint, it is never called. Not sure why
}

Thanks for any asistance.

Upvotes: 0

Views: 84

Answers (1)

Just Shadow
Just Shadow

Reputation: 11921

What you are facing is called Deferred Execution.
Which means that your query is not executed until you use it somewhere.
Here is a part from the documentation:

Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. Deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations. In the best case, deferred execution enables only a single iteration through the source collection.

And in order to execute your statement you just have to use it. The simplest way might be just by calling

myObject.ToList()

Also it will be executed in case you use functions which require the values to be populated (like Sum, Average, etc)

Upvotes: 3

Related Questions