繁体   English   中英

如何从列表中返回对象属性

[英]How to return object property from list

我有一个带有属性的对象列表:

public int Id { get; set; }
public string Name { get; set; }

我的清单是:

List<CategoriesList> Categories { get; set; }

我该如何编写将通过参数传入ID返回对象名称的方法。 我该如何退货?

就像是

return Categories.Select(x => x.Id == id).Name

但这没有意义。

您可以尝试以下方法:

CategoriesList list = Categories.FirstOrDefault(x => x.Id == id);

return (list != null) ? list.Name : null;

您可以尝试以下方法:

return Categories.Where(x => x.Id == id).Select(x=>x.Name);

从上面可以看到,您可以根据拥有的ID过滤类别,然后选择Name

但是,由于我假设Categories是唯一的,因此您也可以尝试以下操作:

// Get the category with the given id. If there is not such a category then the method
// SingleOrDefault returns null.
var category = Categories.SingleOrDefault(x => x.Id == id);

// Check if the category has been found and return it's Name. 
// Otherwise return an empty string.
return category != null ? category.Name : string.Empty;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM