简体   繁体   English

如何使用LINQ选择与ID对应的名称

[英]How to select name corresponding the id using LINQ

I have a class points.cs which has members : 我有一个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>();`

Now this list object contains data: 现在,此列表对象包含数据:

list: 清单:

 Id    Name
  1    abc
  2    def
  3    ghi
  4    jkl

What i have to do is to get the Name corresponding to the id number providing in my code using LINQ query from list object. 我要做的是使用LINQ查询从列表对象中获取与代码中提供的ID号相对应的名称。

My try which os obviously wrong is: 我的尝试显然是错误的是:

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

Please correct me, I am not good in LINQ ? 请纠正我,我对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

Greetings you may want to go like this using lambda expression: 您可能希望使用lambda表达式像这样问候:

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

Goodluck 祝好运

It should be 它应该是

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

First you find your object, then select its Name :) 首先,找到您的对象,然后选择其名称:)

Selects first that meats the condition return null if not found 首先选择肉类条件,如果找不到,则返回null

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

in c# 6 use so you don't have to check if item is found 在c#6中使用,因此您不必检查是否找到了项

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

this will return null or the Name value. 这将返回null或Name值。

Selects first that meats the condition throws exception if not found 如果未找到则首先选择将条件抛出异常的条件

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

with this it's safe to use list.Single(obj=>obj.Id == 2).Name; 这样就可以安全地使用list.Single(obj => obj.Id == 2).Name; list.First(obj=>obj.Id == 2).Name; list.First(obj => obj.Id == 2)。名称; You will not get null unless the Name is null just an exception. 除非Name为null只是一个例外,否则您不会得到null。

If you are using some sort of LINQ to data server (EF,NH,Mongo) some solutions will act a bit differently then when doing in memory query For more info on Single vs First check out LINQ Single vs First 在内存的查询做有关单VS首先检查的详细信息出来的时候如果你正在使用某种形式的LINQ到数据服务器(EF,NH,蒙戈)一些解决方案将扮演一个有点不同然后VS首先LINQ单

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

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