Manikandan
Manikandan

Reputation: 627

Error in LINQ query processing

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

Upvotes: 1

Views: 96

Answers (3)

KyorCode
KyorCode

Reputation: 1497

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.

Upvotes: 0

Maarten
Maarten

Reputation: 22945

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062512

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;
    

Upvotes: 5

Related Questions