简体   繁体   中英

How to select name corresponding the id using LINQ

I have a class points.cs which has members :

  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.

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 ?

您的查询必须是:

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:

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

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

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

this will return null or the Name value.

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.First(obj=>obj.Id == 2).Name; You will not get null unless the Name is null just an exception.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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