2017-09-10 40 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

相關問題