1

实际上,我正在尝试按城市对学生列表进行分组。当我执行此操作时,我在 s2.City 附近的 LINQ 语句中出现“对象引用”错误。

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();
        }
    }

谁能帮我吗?

提前致谢

4

3 回答 3

5

您有一个包含 10 个项目的数组,并且只初始化了 5 个。另外 5 个是null因为数组具有固定长度。这意味着s2.City将导致NullReferenceException. 所以其中之一:

  • 不要超大数组:

    Student[] s = new Student[5];
    
  • 使用 aList<T>而不是数组:

    List<Student> s = new List<Student>();
    ///
    s.Add(new Student { ... }); // etc
    
  • 检查null

    var groupQuery = from s2 in s
                     where s2 != null
                     group s2 by s2.City;
    
于 2012-08-09T10:18:43.273 回答
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.

于 2012-08-09T10:21:01.627 回答
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);
            }
        }

    }

您必须遍历组,然后才能访问该组中的学生。

希望有帮助。

于 2012-08-09T10:30:07.107 回答