使用lambda表达式获取第一个项的属性

3

在C#中,我将使用lambda表达式,我有下面的代码:

var item = dbContext.Products.ToList();

如何获取Product表的属性。


4
你的问题有点不清楚。你是想要一个关于“Product”某个属性的列表,还是想了解一个“Product”的属性?请明确表述。 - Alexander Derck
你想要列表中每个项目的产品属性还是只要一个项目的? - Ian
3个回答

2

尝试这个

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

1
如果列表为空,他将在此处获得NullReferenceException。 - Jakub Szumiato
1
在C#6中,您可以执行 var item = dbContext.Products.FirstOrDefault()?.Name; 这将在尝试访问名称属性之前检查 Product 是否为null。 - Alexander Derck

1
使用Lambda表达式,通常可以访问和读取“列表”或在这种情况下,IQueryable对象中的信息。
使用您的代码,您可以像这样访问对象:
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;
}

您的问题可能会开启其他方式,包括反思探索对象而没有明确定义的类...

1
如果你想使用lambda表达式获取每个产品的属性,则在查询时应该创建一个类似于x => x.Prop的lambda表达式。
if (dbContext.Products != null){
    var list = dbContext.Products.ToList();
    var query = list.Select(x => x.Prop //your property will appear here...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接