C# 从具有列表的对象列表中获取唯一值<;字符串>;作为财产
为了便于说明,我使用了一个简单的Employee类,其中包含多个字段和一个方法来删除C# 从具有列表的对象列表中获取唯一值<;字符串>;作为财产,c#,asp.net,visual-studio-2010,linq,C#,Asp.net,Visual Studio 2010,Linq,为了便于说明,我使用了一个简单的Employee类,其中包含多个字段和一个方法来删除Certifications属性中的多次出现 public int EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } private List<string> certifications = new L
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;
}
要从列表中的所有员工那里获得所有独特认证的列表,但我想在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?)
无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(是否缺少强制转换?)
如何从员工对象列表中获取唯一认证列表 如果我理解的话,您需要一份所有员工的唯一认证列表。这将是以下人员的工作:
您希望使用SelectMany,它允许您选择子列表,但以展开形式返回它们:
stringList = empList.SelectMany(emp => emp.Certifications).Distinct().ToList();
您可以尝试使用SelectMany扩展名
var employeeCertifications = (from e in employeeList select e.Certifications).SelectMany(x => x).Distinct();
如果要为变量设置类型,请尝试
Select()
:
List<string> employeeCertifications =
employeeList.Select(e => e.Certifications).Distinct().ToList();
列出员工认证=
Select(e=>e.Certifications).Distinct().ToList();
我知道我必须接近,这是一行:)如果EmployeeId是唯一标识符,那么我建议您使用EmployeeId覆盖GetHashCode和Equals。另外,将列表证书设置为哈希集(而不是列表),以避免在员工中重复。这仅用于说明目的,但感谢您指出这一点,我将在工具集中归档此证书。
stringList = empList.SelectMany(emp => emp.Certifications).Distinct().ToList();
var employeeCertifications = (from e in employeeList select e.Certifications).SelectMany(x => x).Distinct();
List<string> employeeCertifications =
employeeList.Select(e => e.Certifications).Distinct().ToList();