2010-06-07 64 views
3

我有以下代碼:添加列表至列表

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

GetDbColumns()返回List<string>功能。 所以columNames的類型是List<List<string>>。 是否有可能創建一個List<string>,所以GetDbColumns的列表中的每個元素被添加到LINQ查詢的結果?

回答

4

您可以使用「選擇多個」建設:

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

或者這裏是使用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(); 

最後,這是另一種方式把它(但它包括有些難看的代碼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();