关于数据表的LINQ查询,连接多个选择

时间:2017-07-19 12:23:44

标签: c# linq datatable

我在数据表上有以下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();

Datatable有一些字段,其中一些在上面:Names,Surname,Second Surname ......等等。

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

我该怎么做?

3 个答案:

答案 0 :(得分: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可以解决这个问题。

答案 1 :(得分:1)

您可以使用SelectMany

轻松地在一个查询中使用它
string[] src = dt.AsEnumerable()
   .SelectMany(row => new[]{ row.Field<String>("Name"),row.Field<String>("Surname"),row.Field<String>("Second Surname")} )
   .Distinct()
   .ToArray();

答案 2 :(得分:1)

在查询语法中它将是

I have main project in src of netbeans.
Inside it, i have:
- othello (it contains my main)
- othello.images (it cointains all my image also backgrounds)
- othello.view (it contains my FXML files)
- othello.model (now nothing)
- othello.controller (it contains the controllers about the fxml files)