2013-06-18 25 views
5

爲了便於說明我有幾個字段和方法的簡單Employee類以去除Certifications財產從對象列表獲取唯一值用List <string>作爲屬性

public int EmployeeId { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 

     private List<string> certifications = new List<string>(); 
     public List<string> Certifications 
     { 
      get { return certifications; } 
      set { certifications = value; } 
     } 

public List<string> RemoveDuplicates(List<string> s) 
     { 
      List<string> dupesRemoved = s.Distinct().ToList(); 
      foreach(string str in dupesRemoved) 
       Console.WriteLine(str); 
      return dupesRemoved; 
     } 

多次出現RemoveDuplicates方法將刪除Employee對象的Certifications屬性中的任何重複字符串。現在考慮我是否有一個Employee對象列表。

Employee e = new Employee(); 
      List<string> stringList = new List<string>(); 
      stringList.Add("first"); 
      stringList.Add("second"); 
      stringList.Add("third"); 
      stringList.Add("first"); 
      e.Certifications = stringList; 
      // e.Certifications = e.RemoveDuplicates(e.Certifications); works fine 

      Employee e2 = new Employee(); 
      e2.Certifications.Add("fourth"); 
      e2.Certifications.Add("fifth"); 
      e2.Certifications.Add("fifth"); 
      e2.Certifications.Add("sixth"); 

      List<Employee> empList = new List<Employee>(); 
      empList.Add(e); 
      empList.Add(e2); 

我可以用

foreach (Employee emp in empList) 
      { 
       emp.Certifications = emp.RemoveDuplicates(emp.Certifications); 
      } 

讓所有唯一認證的列表,從所有在冊員工,但我想這樣做的LINQ,一個類似於

stringList = empList.Select(emp => emp.Certifications.Distinct().ToList()); 

這給我一個錯誤說

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.List<string>>' to 'System.Collections.Generic.List<string>'. An explicit conversion exists (are you missing a cast?) 

如何從員工對象列表中獲取唯一認證列表?

+1

如果EmployeeId是唯一標識符,那麼我建議您使用EmployeeId重寫GetHashCode和Equals。還使List 認證HashSet(而不是List)不允許在Employee中重複。 – Paparazzi

+0

這僅用於說明目的,但感謝您指出這一點,我將在工具集中將此文件歸檔。 – wootscootinboogie

回答

18

如果我明白了,您需要所有員工中所有獨特認證的列表。這將是SelectMany工作:

var uniqueCerts = empList.SelectMany(e => e.Certifications).Distinct().ToList(); 
+1

我知道我必須接近,而且這是一個單行的:) – wootscootinboogie

3

你想用的SelectMany,它可以讓你選擇子列表,但返回他們在一個扁平的形式:

stringList = empList.SelectMany(emp => emp.Certifications).Distinct().ToList(); 
0

您可以嘗試使用的SelectMany擴展?

var employeeCertifications = (from e in employeeList select e.Certifications).SelectMany(x => x).Distinct();