I have one List with collection of object arrays.I am using following code to collect all EmployeeIDs
List<string> employeeIds= new List<string>();
var employeeFields = employees.Items.Select(c => c.EmployeeFields ).ToList();
foreach(var objectArray in employeeFields )
{
foreach(var item in objectArray)
{
if(item is EmployeeID)
{
employeeIds.Add(item.ToString());
}
}
}
public partial class EmployeeId
{ private string itemField; /// <remarks/>
public string Item { get {
return this.itemField; }
set { this.itemField = value; }
}
}
Here EmployeeFields consist of an object array.How can i do this in single linq query Live Example http://rextester.com/VJB79010
You can use SelectMany
and OfType
to do this in one go:
var employeeIds = employees.Items
.Select(c => c.EmployeeFields) // Select the fields per employee
.SelectMany(fields => fields) // Flatten to a single sequence of fields
.OfType<EmployeeID>() // Filter to only EmployeeID fields
.Select(id => id.Item) // Convert to strings
.ToList(); // Materialize as a list
Or slightly fewer lines of code, but perhaps more tricky to understand:
var employeeIds = employees.Items
.SelectMany(c => c.EmployeeFields) // Select the fields per employee and flatten
.OfType<EmployeeID>() // Filter to only EmployeeID fields
.Select(id => id.Item) // Convert to strings
.ToList(); // Materialize as a list
See more on this question at Stackoverflow