开发者

LINQ select non-empty strings

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

I want to convert an array of S into string a开发者_开发知识库rray, containing all non-empty unique As and Bs. What is the most efficient way for that?

Regards,


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜