Retrieving unique values ​​from a list of objects with a list of <string> as a property

For illustrative purposes, I have a simple Employee class with several fields and a method for removing multiple occurrences in the Certifications property

 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; } 

The RemoveDuplicates method will remove any duplicate rows in the Certificates property of the Employee object. Now consider if I have a list of Employee objects.

  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); 

I could use

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

to get a list of ALL unique certificates from all employees on the List, but I would like to do it in LINQ, something similar to

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

it gives me an error saying

 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?) 

How can I get a list of unique certificates from a list of Employee objects?

+6
source share
3 answers

If I understand, you need a list of all unique certificates among all employees. This would be work for SelectMany :

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

You want to use SelectMany, which allows you to select sub-lists, but returns them in flattened form:

 stringList = empList.SelectMany(emp => emp.Certifications).Distinct().ToList(); 
+3
source

Can you try using the SelectMany extension?

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

Source: https://habr.com/ru/post/947564/


All Articles