0

If I have a StringValues, with following possible values:

  • "AString"
  • ["OnlyString"]
  • ["FirstString", "IDontCare"]

How can I use C# pattern matching to extract a non-null first string with a one-liner?

I was expecting something like this to work, but it does not:

if (myStringValues is [{} myString, _] )
   something(myString)

2 Answers 2

3

x is [{} myString, ..] is a pattern that will match against new StringValues("foo"), new StringValues(["foo"]) and new StringValues(["foo", "bar", (...)])

_ means discard exactly one

.. means discard any (including none)

if (myStringValues is [{} myString, ..])
{
    something(myString);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Note that the var pattern will match even if the first item is null, whereas {} will only match non-null, so using var changes the semantics from OP's question. StringValues items are nullable.
In other words, it will also match new StringValues([null]), which OP doesn't want based on "non-null first string".
might need to edit to if (stringValues is [{} myString, ..]) which should be the answer even according to @madreflection
Thank you for the comments, updated the answer to better align with OP description.
0

While writing the question, I found that it's possible to solve this, but I could not find a way to do it with a one-liner like I was expecting:

// var stringValues = new StringValues(["a", "b"]);
// var stringValues = new StringValues(["a"]);
var stringValues = new StringValues("a");
var actual = stringValues switch
{
    [{ } only, _ ] => only,
    [{ } first] => first,
    _ => null
};
Assert.Equal("a", actual);

2 Comments

You have the only and first names swapped here.. The _ after only means that there's something else, making it not "only".
Anyway, you can use FirstOrDefault on StringValues to achieve the same thing, and if you don't want to allow more than two, check the Count property, first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.