15

There is a struct S with 2 string fields: A and B.

I want to convert an array of S into string array, containing all non-empty unique As and Bs. What is the most efficient way for that?

Regards,

1 Answer 1

22
var myArray = S.Select( x => new [] { x.A, x.B })
               .SelectMany( x => x)
               .Where( x=> !string.IsNullOrEmpty(x))
               .Distinct()
               .ToArray();

Above only works if the unique constraint is on the resulting collection - if you need a unique constraint on the set of A's and B's the following would work:

var As = S.Select(x => x.A)
          .Where( x=> !string.IsNullOrEmpty(x))
          .Distinct();
var Bs = S.Select(x => x.B)
          .Where( x=> !string.IsNullOrEmpty(x))
          .Distinct();

var myArray = new[] { As, Bs }.SelectMany(x => x).ToArray();

var myArray = As.Concat(Bs).ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

@Joey: Yea, updated - assumption is uniqueness is required on the A's and B's not on the resulting collection, otherwise first approach would be better
For the record, As.Concat(Bs) would do the same as the SelectMany
@Claus Jørgensen: Doh! And its much simpler and readable, edited that in.

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.