Master
Master

Reputation: 33

Get the first item property with lambda expression

In C#, I'm going to use lambda expression, I have such a code

var item = dbContext.Products.ToList();

How can i get a property of Product table.

Upvotes: 3

Views: 3161

Answers (3)

Ian
Ian

Reputation: 30813

If you want to get the property for each product with lambda expression, then you should make a lambda expression like x => x.Prop when you do your query

if (dbContext.Products != null){
    var list = dbContext.Products.ToList();
    var query = list.Select(x => x.Prop //your property will appear here...
}

Upvotes: 1

Othello  .net dev
Othello .net dev

Reputation: 438

With Lamba expression normally you can access and read information from "list" or in this case, IQueryable objects.

With your code you can access to objects with something like this:

var item = dbContext.Products.FirstOrDefault();
// item may be null if products table is empty
if (item != null)
{
    // now you can access at object properties (example)
    var data = item.PropertyData;
}

Your question may open others way that including reflection for exploring object without well known class definition...

Upvotes: 1

Hayot
Hayot

Reputation: 251

try this

var item = dbContext.Products.FirstOrDefault().Name;

Upvotes: 2

Related Questions