4

My task is to use Pattern Matching to make an Employee selection where the Email will not be null and the first two languages of the employee will be "ru" and "en"
How do I make a check for not null and check the first two elements of the Languages ?

Here's what I have

public static string IsRuEnWithEmail(Employee emp) => emp switch
{
    { Email:  != null, Languages: { "ru", "en" } } =>
        $"{emp.FCs}, {emp.Email}, {emp.Role}",
    _ => "",
};

It doesn't work at all
Errors say that it is impossible to compare this way

7
  • 7
    Why make it complicated in an expression? What's the win here? Any new programmer has to look 5x to understand it. If you can write software everybody understands, you on the right track. Try to write it in a non-expression way. Commented Dec 1, 2022 at 10:34
  • @JeroenvanLangen This is the first part of the assignment from the university, then there are more complex ones
    – vcdk
    Commented Dec 1, 2022 at 10:41
  • 1
    "This is the first part of the assignment" the first part is to make it as an exprression?
    – Mong Zhu
    Commented Dec 1, 2022 at 10:51
  • 4
    BTW: I don't know if it's just me, but a string return type from a method with name IsXXX() would be rather surprising for me. And I'd have to refer to docs to see what it does.
    – Fildor
    Commented Dec 1, 2022 at 11:04
  • 1
    @Fildor i'm with you and he is calling it "checking".
    – Ralf
    Commented Dec 1, 2022 at 11:09

1 Answer 1

4

Pattern matching is relatively new in C#, even more for list patterns which begin with C# 11 which was released this month.

A not null matching is created with { }.
A partial list matching is created with [item1, item2, ..]

All together:

// We expect a method prefixed with "Is" to return a boolean
// but OP provided this signature
public static string IsRuEnWithEmail(Employee emp) => emp switch
{
    { Email: {}, Languages: ["ru", "en", ..] } => $"{emp.FCs}, {emp.Email}, {emp.Role}",
    _ => "",
};

Working demo here.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.