【发布时间】:2016-12-26 13:25:34
【问题描述】:
我有一个类 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>();`
现在这个列表对象包含数据:
列表:
Id Name
1 abc
2 def
3 ghi
4 jkl
我要做的是使用来自列表对象的 LINQ 查询来获取与我的代码中提供的 id 号相对应的名称。
我的尝试明显错误的操作系统是:
string nameFetchedId=list.Select(Name).Where(obj=>obj.Id=2) //result returned will be "def"
请纠正我,我不擅长 LINQ 吗?
【问题讨论】:
-
list.Single(o => o.Id == 2).Name? -
@David 如果列表为空,此代码将抛出异常。
-
@Lepijohnny:正确。并且有多种方法来处理它,这取决于这对被调用的业务逻辑意味着什么。这超出了问题的范围。
-
@David 同意你的观点,这只是一个观察。