[英]Getting unique values from a list of objects with a List<string> as a property
出於說明目的,我有一個簡單的 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 對象列表中獲取唯一認證列表?
如果我明白,您想要一份所有員工中所有獨特認證的清單。 這將是SelectMany的工作:
var uniqueCerts = empList.SelectMany(e => e.Certifications).Distinct().ToList();
您想使用 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.