C# LINQ创建嵌套对象的通用列表
如何从另一个C# LINQ创建嵌套对象的通用列表,c#,.net,list,linq,generics,C#,.net,List,Linq,Generics,如何从另一个列表中获取包含另一个列表的列表 情况如下: 我有一个列表。每个条目都包含一个数据库结构 public partial class DatabaseStructure { public string TableSchema { get; set; } public string TableName { get; set; } public string ColumnName { get; set; } public bool? IsPrimaryKey
列表中获取包含另一个列表的列表
情况如下:
我有一个列表
。每个条目都包含一个数据库结构
public partial class DatabaseStructure
{
public string TableSchema { get; set; }
public string TableName { get; set; }
public string ColumnName { get; set; }
public bool? IsPrimaryKey { get; set; }
}
我也有
public class Table
{
public string Name { get; set; }
public string Schema { get; set; }
public List<Column> Columns { get; set; }
}
public class Column
{
public string Name { get; set; }
public bool? IsPrimaryKey { get; set; }
}
我的解决方案的问题是,我的查询不是一个通用列表
有人能给我指出正确的方向吗?林w到这儿来对吗?如果是,我如何获得想要的结果
提前谢谢
前言:我更喜欢(并建议)使用Linq和扩展方法语法,而不是使用from
,group
,into
关键字,因为它更具表现力,如果您需要执行更高级的Linq操作,您仍然需要使用扩展方法
首先,您的输入是非规范化的(我假定运行SELECT…FROM INFORMATION\u SCHEMA.COLUMNS
)的输出,其中每一行都包含重复的表信息,因此使用GroupBy
按表标识符将行分组在一起(不要忘记同时使用表架构和表名来唯一标识表!)
然后将每个组(i分组
)转换为表
对象
然后,通过执行内部从i分组
组中选择
,然后执行.ToList()
来填充表.列
列表,以获得具体的列表
对象
我的表情是:
List<DatabaseStructure> input = ...
List<Table> tables = input
.GroupBy( dbs => new { dbs.TableSchema, dbs.TableName } )
.Select( grp => new Table()
{
Name = grp.Key.TableName,
Schema = grp.Key.TableSchema,
Columns = grp
.Select( col => new Column()
{
Name = col.Name,
IsPrimaryKey = col.IsPrimaryKey
} )
.ToList()
} )
.ToList()
列表输入=。。。
列表表=输入
.GroupBy(dbs=>new{dbs.TableSchema,dbs.TableName})
.Select(grp=>newtable()
{
Name=grp.Key.TableName,
Schema=grp.Key.TableSchema,
列=grp
.选择(列=>新列()
{
名称=列名称,
IsPrimaryKey=列IsPrimaryKey
} )
托利斯先生()
} )
托利斯先生()
好的,我自己刚找到答案
这是:
var query =
(from t in result
group t.TableName by t.TableName
into tn
select new Table
{
Name = tn.Key,
Schema = (from s in result where s.TableName == tn.Key select s.TableSchema).First(),
Columns = (from c in result
where c.TableName == tn.Key
select new Column
{
Name = c.ColumnName,
IsPrimaryKey = c.IsPrimaryKey
}).ToList()
});
var query =
(from t in result
group t.TableName by t.TableName
into tn
select new Table
{
Name = tn.Key,
Schema = (from s in result where s.TableName == tn.Key select s.TableSchema).First(),
Columns = (from c in result
where c.TableName == tn.Key
select new Column
{
Name = c.ColumnName,
IsPrimaryKey = c.IsPrimaryKey
}).ToList()
});