LINQ选择非空字符串

noo*_*ber 12 c# linq

有一个带有2个字符串字段的结构S:A和B.

我想将一个S数组转换为字符串数组,包含所有非空的唯一As和Bs.最有效的方法是什么?

问候,

Bro*_*ass 15

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

上面只有在结果集合上有唯一约束时才有效 - 如果你需要对A和B的集合有唯一约束,则以下方法可行:

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();
Run Code Online (Sandbox Code Playgroud)

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

var myArray = As.Concat(Bs).ToArray();
Run Code Online (Sandbox Code Playgroud)