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

C# 如何从列表中返回对象属性,c#,C#,我有一个具有以下属性的对象列表: public int Id { get; set; } public string Name { get; set; } 我的名单是: List<CategoriesList> Categories { get; set; } 但这毫无意义。您可以尝试以下方法: CategoriesList list = Categories.FirstOrDefault(x => x.Id == id); return (list != null) ?

我有一个具有以下属性的对象列表:

public int Id { get; set; }
public string Name { get; set; }
我的名单是:

List<CategoriesList> Categories { get; set; }
但这毫无意义。

您可以尝试以下方法:

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筛选类别,然后选择
名称

但是,由于我假设
类别
是唯一的,因此您也可以尝试以下方法:

// 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;

类似于返回类别。选择(x=>x.Id==Id)。命名但没有意义。为什么没有意义?@user3852834你就快到了。当您运行
选择时,您将获得一个集合。尝试选择第一条记录;)@user3852834总是查看返回值的类型——正如ben已经说过的:您将得到一个categorieslist的集合。这是因为LINQ不知道Id对您来说是“唯一的”,例如,可能有更多的项目具有相同的Id,或者说具有相同的名称-这就是为什么您在运行select时会得到一个集合。@user3852834:需要更多帮助吗?
// 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;