Reputation: 27
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 ?
Upvotes: 0
Views: 17976
Reputation: 2561
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
Upvotes: 0
Reputation: 3228
Greetings you may want to go like this using lambda expression:
string strName = list.where( x => x.id == 2).SingleOrDefault()?.Name;
Goodluck
Upvotes: 3
Reputation: 1820
It should be
string nameFetchedId=list.SingleOrDefault(obj=>obj.Id==2)?.Name;
First you find your object, then select its Name :)
Upvotes: 0
Reputation: 789
Your query needs to be:
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
Upvotes: 6