Aks1
Aks1

Reputation: 35

LINQ Query skips without exception. Why?

I have a method that gets a nested array as parameter:

Number[][] data 

where Number is my very simple class that inherits from INotifyPropertyChange.

And then i have a statement like this:

double[] max = (double[])data.Select(crArray => crArray.Select( cr => cr.ValueNorm ).Max());

When I'm trying to watch it in the debugger it just skips it and the whole method though no exception pops out.

What is the answer? And what is the better way to do it.

I can use loops, of course - but it looks so dirty and long. So LINQ is preferrable

P.S. I'm using VS2008 SP1

Upvotes: 1

Views: 228

Answers (3)

Amy B
Amy B

Reputation: 110161

Are you sure that the Select method returns an array? Casting + generics = code smell

Try this:

double[] max = data
  .Select(crArray => crArray.Select( cr => cr.ValueNorm ).Max())
  .ToArray();

Conversion Method - (ToArray) allocates a new array and populates it. Bound by the restrictions of methods.

Down Casting - Allows you to change the type of the reference to an object instance. Only the actual instance type, or some type that the instance type inherits from are allowed. Anything else gives a runtime exception.

Explicit Conversion Operator - uses the syntax of down casting, to achieve the effect of conversion. It's really a Conversion Method. This is an endless source of confusion for people trying to understand casting.

Consider this code:

// reference type is IEnumerable<string>, instance type is string[]
IEnumerable<string> myArray =
  new string[3] { "abc", "def", "ghi" };
// reference type is IEnumerable<string>, instance type is ???
IEnumerable<string> myQuery = myArray
  .Select(s => s.Reverse().ToString());

//Cast - works
string[] result = (string[]) myArray;
//Cast - runtime exception: System.InvalidCastException
result = (string[])myQuery;
//Conversion - works
result = myQuery.ToArray();

Why didn't you get a runtime exception in vs? I don't know.

Upvotes: 1

Nicolas Dorier
Nicolas Dorier

Reputation: 7465

Have you try to iterate through max ? I think this did not throw, because you have not iterated through the result of your request (Linq launch your request only after the first call to GetEnumerator.

The ToArray method iterates throught the enumerable of your request, and copy every thing in an array. I think it's the difference.

Upvotes: 0

Sergio
Sergio

Reputation: 8259

Usually this type of behaviour means that your source code files are not up to date. Try deleting all .bin and .pdb files from the output directory and rebuild.

Upvotes: 1

Related Questions