2017-07-19 91 views
1

我有以下LINQ查询的数据表:LINQ查询,加入多个选择

string[] sourceNames = this.dt 
        .AsEnumerable() 
        .Select<System.Data.DataRow, String>(x => x.Field<String>("Name")) 
        .ToArray(); 

string[] sourceSurnames = this.dt 
     .AsEnumerable() 
     .Select<System.Data.DataRow, String>(x => x.Field<String>("Surname")) 
     .ToArray(); 

string[] sourceSecondSurnames = this.dt 
     .AsEnumerable() 
     .Select<System.Data.DataRow, String>(x => x.Field<String>("Second Surname")) 
     .ToArray(); 

string[] src = sourceNames.Union(sourceSurnames).Union(sourceSecondSurnames).ToArray(); 

表具有某些领域,他们中的一些上面:名,姓,二姓......等等。

我在这里要做的是只加入一个三个linq查询。最终目标是获得一组字符串,即src。

我该怎么做?

+0

那么,什么是不与上面的代码工作? – DavidG

+0

你目前的代码是做什么的?这与你想要的**有什么不同? – mjwills

回答

1

你可以用SelectMany有它在一个单一的查询容易:

string[] src = dt.AsEnumerable() 
    .SelectMany(row => new[]{ row.Field<String>("Name"),row.Field<String>("Surname"),row.Field<String>("Second Surname")}) 
    .Distinct() 
    .ToArray(); 
1
  var everything = dt 
      .AsEnumerable() 
      .Select(x => x.Field<string>("Name")) 
      .ToArray().Concat(dt.AsEnumerable() 
      .Select(x => x.Field<string>("Surname")) 
      .ToArray()).Concat(dt 
       .AsEnumerable() 
       .Select(x => x.Field<string>("Second Surname")) 
       .ToArray()); 

使用Concat可以解决这个问题。

+0

这是一个问题或答案? – DavidG

+0

这是一个答案和一个问题,用户提出了一个问题,以检查它是否解决了他的问题。 – milorads

+0

答案不应该包含问题,但这是评论的目的。 – DavidG

1

在查询语法这将是

var src = (from row in dt.AsEnumerable()    
      from n in new[]{ row.Field<String>("Name"),row.Field<String>("Surname"),row.Field<String>("SecondSurname")} 
      select n).Distinct().ToArray();