0

Im just starting to learn how to use LinQ, I want to only show grades that are 9 and 10 from a list i have but when trying to use var and foreach it wont let me, not sure why.

This is the list i was provided:

int[] grades= { 5, 9, 7, 8, 6, 9, 5, 7, 7, 4, 6, 10, 8 };

And here im trying to do the query:

        var grades1 = from s in grades
        where s.grades>= 9 
        select s;

        foreach (var cal in grades)
        Console.WriteLine(cal.grades);

The thing is that it shows an error when doing s.grades and cal.grades. I cant change the int[]grades.

4
  • Can you please share the error you are getting? Commented Feb 28, 2022 at 22:40
  • try cal.grades.ToString(); Commented Feb 28, 2022 at 22:42
  • 1
    You're assigning to grades1 and then using grades Commented Feb 28, 2022 at 22:43
  • 1
    The variable s represents an element of grades. Since grades is an int[], s is an int. So it needs to be where s >= 9. Commented Feb 28, 2022 at 22:44

2 Answers 2

1

The following works:

int[] grades = { 5, 9, 7, 8, 6, 9, 5, 7, 7, 4, 6, 10, 8 };
var grades1 = from s in grades
              where s >= 9
              select s;

foreach (var cal in grades1)
    Console.WriteLine(cal);

s is an int so you can't qualify it. You are selecting an int element of an array of ints

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much this helped alot! As you said the problem was with the int element
0

try this

 int[] grades = { 5, 9, 7, 8, 6, 9, 5, 7, 7, 4, 6, 10, 8 };

var grades1 = from s in grades
              where s >= 9
              select s;

foreach (var cal in grades1)
{
    Console.WriteLine(cal);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.