出于说明目的,我有一个简单的 Employee 类,其中包含多个字段和一个删除Certifications
属性中多次出现的方法
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?)
如何从 Employee 对象列表中获取唯一认证列表?