tags:

views:

125

answers:

3

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

+1  A: 

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.

Sergio
+1  A: 

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.

David B
No it's not. It returns IEnumerable<double>, but I thought that casting and ToArray() is doing the same thing - transforming IEnumerable to Array.Your method actually works, but what is the difference? And why this strange Visual Studio behavior?
Aks1
Yeah, I'm really thought that it will use conversion operator.Thx for answer)
Aks1
A: 

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.

Nicolas Dorier