2017-09-10 37 views
1

请考虑我不擅长英语。如何查询具有相同值的班级

Class'Student'列表绑定到ListBox,Displaymemeber是'group'字段。

我的目标是显示没有重叠的组。 (只是A和B)

但在这里我的代码显示这样。

ListBox

我怎么能只显示A和B?

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     Student st1 = new Student("Kim", 15, Group.A); 
     Student st2 = new Student("Lee", 15, Group.A); 
     Student st3 = new Student("Park", 15, Group.B); 

     Student.Add(st1);   
     Student.Add(st2);   
     Student.Add(st3); 

     listBox1.DataSource = Student.LstStudent; 
     listBox1.DisplayMember = "group"; 
    } 
} 


public enum Group 
{ 
    None, 
    A, 
    B, 
    C 
} 

public class Student 
{ 
    private static List<Student> _LstStudent = new List<Student>(); 
    public static List<Student> LstStudent 
    { 
     get 
     { 
      return _LstStudent; 
     } 
    } 

    public Group group { get; set; } 
    public string name { get; set; } 
    public int age { get; set; } 


    public Student(string name, int age, Group group) 
    { 
     this.name = name; 
     this.age = age; 
     this.group = group; 
    } 

    public static void Add(Student student) 
    { 
     LstStudent.Add(student); 
    } 
} 

回答

0

如果你的意图是只显示组,你可以使用LINQ来过滤你的List<Student>

尝试改变

listBox1.DataSource = Student.LstStudent; 
listBox1.DisplayMember = "group"; 

listBox1.DataSource = Student.LstStudent.Select(x => x.group).Distinct().ToArray(); 
+0

感谢。有用。但添加'.ToArray()' – ysOh

+0

@YeongSeokOh我已经更新了我的答案,包括'.ToArray()'方法链。我不确定'DataSource'属性是否需要一个数组或者只需要一个'IEnumerable'。如果它现在回答你的问题,请接受答案,谢谢! –

+0

我可以再问一个吗?怎样才能让所有的学生这个小组是A? – ysOh

相关问题