Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ select non-empty strings

Tags:

c#

linq

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,

like image 472
noober Avatar asked Jul 31 '11 22:07

noober


1 Answers

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();
like image 165
BrokenGlass Avatar answered Oct 07 '22 18:10

BrokenGlass