1

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?

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.