Add list to list

I have the following code:

var columnNames = (from autoExport in dataContext.AutoExports
               where autoExport.AutoExportTemplate != null
                  && ContainsColumn(autoExport.AutoExportTemplate, realName)
               select GetDbColumnNames(autoExport.AutoExportTemplate, realName)).ToList();

If the function GetDbColumns()returns List<string>. So columNames has a type List<List<string>>. Is it possible to create List<string>, therefore, each element of the GetDbColumns list is added to the LinQ query result?

+3
source share
1 answer

You can use the "select many" construct:

var columnNames = (
    from autoExport in dataContext.AutoExports
    where autoExport.AutoExportTemplate != null
          && ContainsColumn(autoExport.AutoExportTemplate, realName)
    from column in GetDbColumnNames(autoExport.AutoExportTemplate, realName)
    select column).ToList();

Or here is an alternative way to use it SelectMany:

var columnNames = (
    from autoExport in dataContext.AutoExports
    where autoExport.AutoExportTemplate != null
          && ContainsColumn(autoExport.AutoExportTemplate, realName)
    select autoExport
).SelectMany(x => x.GetDbColumnNames(autoExport.AutoExportTemplate, realName))
.ToList();

And finally, this is another way to deliver (but it includes somewhat ugly code x => x):

var columnNames = (
    from autoExport in dataContext.AutoExports
    where autoExport.AutoExportTemplate != null
          && ContainsColumn(autoExport.AutoExportTemplate, realName)
    select autoExport.GetDbColumnNames(autoExport.AutoExportTemplate, realName)
).SelectMany(x => x).ToList();
+4
source

Source: https://habr.com/ru/post/1748806/