0

I am getting Invalid Operation Error in following code.

 int m = l_score.Min();

where l_score is int list. Why this would happen ?

Edit: Code

 List<int> l_origin = new List<int>();
 List<int> l_k = new List<int>();
 List<int> l_score = new List<int>();



 for (int i = 0; i < 9; i++)
        {
            if (box_matrix[i, 5] == 0 | box_matrix[i, 5] == 1 | box_matrix[i, 5] == 2)
            {

                for (int k = 1; k < 5; k++)
                {

                    if (box_matrix[i, k] == 0)
                    {
                        int scr = 9;
                        l_origin.Add(box_matrix[i, 0]);
                        l_k.Add(k);
                        scr = score_the_move(box_matrix[i,0],k);
                        l_score.Add(scr);

                    }
                }
            }
        }


        //find the best move
       int m = l_score.Min();
       int min_index =  l_score.IndexOf(m);
       machine_line(l_origin[min_index], l_k[min_index]);
       l_origin.Clear();
       l_k.Clear();
       l_score.Clear();
John Saunders
  • 160,644
  • 26
  • 247
  • 397
John Watson
  • 869
  • 3
  • 16
  • 32

3 Answers3

2

You need to import System.Linq:

using Sytem.Linq;

and then your line will work:

int m = l_score.Min();

I bet you are seeing this error: InvalidOperationException (Sequence contains no elements). It occurs when the list is empty.

John Woo
  • 258,903
  • 69
  • 498
  • 492
2

I'm guessing l_score is empty, which is why you're getting that exception. Look at the message of the exception to get more detail.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • i checked, your are correct that `l_score` is empty. but why it is not getting populated ? – John Watson Sep 24 '12 at 02:15
  • Because your code to add an item is never called. Could be a logic error with your if statements or just an edge case scenario. – D Stanley Sep 24 '12 at 02:17
1

Invalid operation exception is thrown when the list contents no elements, if you call the .Min() method.

Found this when decompiling IEnumerable:

<exception cref="T:System.InvalidOperationException"><paramref name="source"/> contains no elements.</exception>
lahsrah
  • 9,013
  • 5
  • 37
  • 67