Reputation: 3839
I have Array of objects SomeObjects[] objects. This 'objects' may contain type of 'Employee', 'Customer' or something else. I wanted to write a linq query if 'objects' contain type of 'Employee' and if his name (Employee.Name) is 'John', I want to get the employeeid.
Is it possible?
Upvotes: 1
Views: 2148
Reputation: 96477
Use the OfType
method to filter objects based on their type, then use the Where
method to filter on the name:
var query = objects.OfType<Employee>()
.Where(e => e.Name == "John")
.Select(e => e.EmployeeId);
This will return the employee IDs for all employees with the name of "John." If you expect only one person to match that criteria, you can replace the Where
method with Single
, or if you want to take the first result use First
. However, if you expect one person but don't know whether they exist, you'll want to use SingleOrDefault
:
Employee result = objects.OfType<Employee>()
.SingleOrDefault(e => e.Name == "John");
if (result != null)
{
Console.WriteLine(result.EmployeeId);
}
Upvotes: 1
Reputation: 164281
Yes. You can use the safe cast operator as
operator in your query to find objects of a specific type and have them cast to that type:
var employees = from obj in objects
let emp = obj as Employee
where emp != null && emp.Name == "John"
select emp;
Upvotes: 2