C# 使用 lambda 表达式选择两列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19120989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:09:18  来源:igfitidea点击:

select two columns using lambda expression

c#

提问by user2835586

I have a table with several columns (clm1-clm10). The datagrid is populated with all columns as follows:

我有一个包含几列 (clm1-clm10) 的表。数据网格填充了所有列,如下所示:

MyTableDomainContext context = new MyTableDomainContext();
dataGrid1.ItemsSource = context.DBTables;
context.Load(context.GetDBTablesQuery());

GetDBTablesQuery()is defined in domainservices.csas follows:

GetDBTablesQuery()定义domainservices.cs如下:

public IQueryable<DBTable> GetDBTables()
{
    return this.ObjectContext.DBTables;
}

How can I displayed only two columns (e.g. clm1 and clm5) using the select lambda expression?

如何使用 select lambda 表达式只显示两列(例如 clm1 和 clm5)?

回答by Jeremy Cook

Is this what you are looking for?

这是你想要的?

GetDBTables().Select(o => new { o.clm1, o.clm5 });

It will result in an anonymous type. If you want it to result in some type you have defined it could something like this:

这将导致匿名类型。如果你希望它产生你定义的某种类型,它可能是这样的:

GetDBTables().Select(o => new MyViewModel { clm1 = o.clm1, clm5 = o.clm5 });