1

Actually, i am trying to group the list of students by city. When i execute this i get "Object Reference" error in LINQ statement near s2.City.

class Groupby
    {
        Student[] s = new Student[10];

        public Groupby()
        {
            s[0] = new Student("Manikandan", "Jayagopi", "Chennai");

            s[1] = new Student("Ganesh", "Bayyanna", "Bangalore");

            s[2] = new Student("Laxman", "Bharghav", "Hyderabad");

            s[3] = new Student("Dinesh","Vellaiyan","Pune");

            s[4] = new Student("Natarajan","Nallathambi","Chennai");
        }

        public void Group()
        {                
            var groupQuery = from s2 in s
                             group s2 by s2.City;

            foreach (Student s1 in groupQuery)
                Console.WriteLine(" {0}", s1.FirstName);

        }
    }

class Program
    {
static void Main()
        {            
            Groupby objGroupby = new Groupby();

            objGroupby.Group();

            Console.ReadLine();
        }
    }

Can anyone help me out?

Thanks in advance

3 Answers 3

5

You have an array of 10 items and have only initialized 5. The other 5 are null since arrays have fixed length. This means that s2.City will cause a NullReferenceException. So one of:

  • don't oversize the array:

    Student[] s = new Student[5];
    
  • use a List<T> instead of an array:

    List<Student> s = new List<Student>();
    ///
    s.Add(new Student { ... }); // etc
    
  • check for null:

    var groupQuery = from s2 in s
                     where s2 != null
                     group s2 by s2.City;
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Marc! When i use as you said in the third option, i get an "unable to cast" error in foreach loop.
1

You create an array with size 10, you only fill the array with 5 objects, so indici 5 to 9 are NULL references. Later, you group by a property of the objects, and voila, thats where it goes wrong, since you're trying to read a property of a NULL reference.

Comments

0
public void Group()
    {
        var groupQuery = from s2 in s
                         where s2 != null
                         group s2 by s2.City;

        foreach (var s1 in groupQuery)
        {
            Console.WriteLine("Group: {0}", s1.Key);
            foreach(var s in s1)
            {
                Console.WriteLine("Student: {0}", s.FirstName);
            }
        }

    }

You have to loop over the groups, before you can access the students in that group.

Hope that helps.

1 Comment

Thank you very much Kyor! That really helped me to sort it out!

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.