gpt4 book ai didi

c# - 如何从表中获取列的子集而不需要 Linq 中的新类型

转载 作者:行者123 更新时间:2023-11-29 12:06:15 24 4
gpt4 key购买 nike

例如如果我有以下类(class):

public class Schema
{
public int SchemaId { get; set; }
public byte[] XsdFile { get; set; }
public byte[] MetadataFile { get; set; }
public byte[] TemplateFile { get; set; }

public string Name { get; set; }
}

我在 Linq 中使用此查询,我将获得所有列:

from s in db.Schemas select s;

如果我只需要 IdName 列以及其他三个字节数组字段的默认值,我需要将其投影到另一个定义的类型或匿名类型或这样的字典:

db.Schemas.ToDictionary(s => s.SchemaId, s => s.Name);

但是,如何使用 LINQ 查询获得相同的类型,即 Schema 本身,该查询将具有这些字节数组的默认值,而不是从表中获取它们?我真的不想创建另一种类型,并且无法使用匿名类型,因为我想从 Web 服务传输它。

最佳答案

选择相关片段为匿名类型,调用.ToList()将数据放入内存,然后投影到新的Schema对象中。

var result = (from s in db.Schemas
select new { s.SchemaId, s.Name })
.ToList()
.Select(s => new Schema
{
SchemaId = s.SchemaId,
Name = s.Name,
XsdFile = new byte[length],
MetadataFile = new byte[length],
TemplateFile = new byte[length]
});

关于c# - 如何从表中获取列的子集而不需要 Linq 中的新类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com