2012-08-09 199 views
1

其实我试图按城市对学生列表进行分组。当我执行此操作时,在s2.City附近的LINQ语句中出现“对象引用”错误。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(); 
     } 
    } 

任何人都可以帮我吗?

预先感谢

回答

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

    } 

在访问该组中的学生之前,您必须遍历组。

希望有所帮助。

+0

非常感谢Kyor!这真的帮我解决了问题! – Manikandan 2012-08-09 10:34:54

5

你具有10项的阵列,并且只初始化5.其他5 null因为数组具有固定长度。这意味着s2.City将导致NullReferenceException。所以之一:

  • 不特大型数组:

    Student[] s = new Student[5]; 
    
  • 使用List<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; 
    
+0

谢谢马克!当我在第三个选项中使用时,我在foreach循环中出现“无法投射”错误。 – Manikandan 2012-08-09 10:26:16

1

您可以创建一个大小为10的数组,因此只能使用5个对象填充数组,因此5号到9号是NULL引用。后来,你通过对象的属性进行分组,并且瞧,那就是它出错的地方,因为你试图读取一个NULL引用的属性。