如何使用 LINQ select 命名对应的 id

How to select name corresponding the id using LINQ

我有一个 class 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 号对应的名称。

我的尝试os明显错误的是:

 string nameFetchedId=list.Select(Name).Where(obj=>obj.Id=2) //result returned will be "def"

请指正,我 LINQ 不好?

应该是

string nameFetchedId=list.SingleOrDefault(obj=>obj.Id==2)?.Name;

首先找到您的对象,然后 select 它的名称 :)

问候你可能想像这样使用 lambda 表达式:

string strName = list.where( x => x.id == 2).SingleOrDefault()?.Name; 

祝你好运

您的查询需要:

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

首先选择符合条件的return如果没有找到则为null

list.SingleOrDefault(obj=>obj.Id == 2); 
list.FirstOrDefault(obj=>obj.Id == 2);

在 c# 6 中使用,因此您不必检查是否找到项目

list.SingleOrDefault(obj=>obj.Id == 2)?.Name; 
list.FirstOrDefault(obj=>obj.Id == 2)?.Name;

这将为 return 空值或名称值。

首先选择符合条件的,如果找不到则抛出异常

list.Single(obj=>obj.Id == 2);
list.First(obj=>obj.Id == 2);

有了这个就可以放心使用了 list.Single(obj=>obj.Id == 2).名称; list.First(obj=>obj.Id == 2).名称; 除非 Name 为 null 只是一个例外,否则您不会得到 null。

如果您正在使用某种 LINQ 到数据服务器(EF、NH、Mongo),一些解决方案的行为将与在内存中查询时有所不同 有关单身与第一次的更多信息,请查看 LINQ Single vs First