6

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

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

GetDBTablesQuery() is defined in domainservices.cs as follows:

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?

4
  • @JeremyCook: Is it matters in this case? Commented Oct 1, 2013 at 16:19
  • possible duplicate of Selecting Many Fields From a Table using Linq and Lamda Expressions Commented Oct 1, 2013 at 16:20
  • It may not, but different frameworks that have controls with the same name sometimes behave differently. Not taking that into consideration has caused me headaches in the past. Commented Oct 1, 2013 at 16:22
  • I wouldn't consider this a duplicate of that. Although the answer may ultimately be the same in many cases, trying to display information in a data grid is not the same as creating a variable. Commented Oct 1, 2013 at 16:24

1 Answer 1

15

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 });
Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks Jeremy, I believe this is what I am looking for. I am using an IQueryable so I m trying to return string values Return GetDBTables().Select(o => new MyDto { clm1 = o.clm1, clm5 = o.clm5 }); But complains about missing domain space MyDto (I know this is a dumb Q but) how is it defined?
MyDto would be a class you have created that only has the properties you want, e.g. clm1 and clm5 in this case. Alternatively, use the anonymous type syntax and don't create a concrete class like MyDto unless you really need to.
I know this is an old post, but this answer/extension was fantastic! Thanks Jeremy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.