sta*_*ver 0 .net c# linq select where
我有一个类 points.cs 有成员:
public class Points
{
public int Id = 0;
public string Name { get; set; }
}
I have a list of these points like this `List<Points> list= new List<Points>();`
Run Code Online (Sandbox Code Playgroud)
现在这个列表对象包含数据:
列表:
Id Name
1 abc
2 def
3 ghi
4 jkl
Run Code Online (Sandbox Code Playgroud)
我要做的是使用列表对象中的 LINQ 查询获取与我的代码中提供的 ID 号相对应的名称。
我的尝试显然是错误的:
string nameFetchedId=list.Select(Name).Where(obj=>obj.Id=2) //result returned will be "def"
Run Code Online (Sandbox Code Playgroud)
请纠正我,我不擅长 LINQ?
您的查询需要是:
string name = list.SingleOrDefault(obj => obj.Id == 2)?.Name; // ?. will prevent the code from throwing a null-reference exception and will return null when a point with Id = 2 does not exist
Run Code Online (Sandbox Code Playgroud)