I want to make a query that returns a specific person (by ID) from person-list (persons).
public Person getThisID(int pID)
{
var res = from p in persons
where p.pID == pID
select p;
return res;
}
But I got an error about casting problems. I tried to cast res
to Person but it doesn't work with that. How can I solve it?
var res= (from p in persons
where p.pID == pID
select p).SingleOrDefault();
return res;
select p;
could potentially return multiple results.
Wrap your query with a .FirstOrDefault();
var res = (from p in persons
where p.pID==pID
select p).FirstOrDefault();
return res;
This will return a null
object if no user is found, or the first user with that Id if many are found.
Alternatively you could use SingleOrDefault()
which will throw an exception if more than one result is found.
Both the SingleOrDefault()
and FirstOrDefault()
methods support passing a filter to them so you could also simplify your query into a 1 line Lambda Statement.
return persons.FirstOrDefault(p => p.pID == pID);
Assuming Persons
is a Person
collection, res
is an IEnumerable<Person>
and not a single person. If you expect only one result, use the Single
method.
That query will return an IEnumerable<Person>
and not a single Person
. That is because the where could return multiple results. Add FirstOrDefault()
to your result and you're good:
public Person getThisID(int pID)
{
var res = from p in persons where p.pID == pID select p;
return res.FirstOrDefault();
}
This will return the first instance that meets the condition otherwise the default, most likely null
.
To shorten things up you could also use a LinQ method with a lambda expression:
return persons.FirstOrDefault(p => p.pID == pID);
//or...
return persons.Single(p => p.pID == pID);
if person is List
then
var data = persons.Where( x => x.PID == pid).SingleOrDefault();
return data
仅使用FirstOrDefault
:
return persons.FirstOrDefault(p=> p.ID == pId);
Try this
public Person getThisID(int pID)
{
Person res= (from p in persons
where p.pID==pID
select p).First();
return res;
}
Should work :)
您可以使用以下代码段
persons.FirstOrDefault(p => p.id == pID);
Very easy:
public Person getThisID(int pID)
{
return persons.FirstOrDefault(p=> p.pID == pID);
}
Please use FirstOrDefault() when returning single value
var res= from p in persons
where p.pID==pID
select p.FirstOrDefault();
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.