爲了便於說明我有幾個字段和方法的簡單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?)
如何從員工對象列表中獲取唯一認證列表?
如果EmployeeId是唯一標識符,那麼我建議您使用EmployeeId重寫GetHashCode和Equals。還使List認證HashSet(而不是List)不允許在Employee中重複。 –
Paparazzi
這僅用於說明目的,但感謝您指出這一點,我將在工具集中將此文件歸檔。 – wootscootinboogie