例如如果我有以下类(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;
如果我只需要 Id
和 Name
列以及其他三个字节数组字段的默认值,我需要将其投影到另一个定义的类型或匿名类型或这样的字典:
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/