namco
namco

Reputation: 6348

LINQ to List<T> gives an error

i have class like below

class Person
{
  public string Name{get;set;}
  public string Surname{get;set;}
  public int Age{get; set;}
}

I have a list like this

List<Person> persons = new List<Person>();

Then there is a method

public Person SelectPerson(string name)
{
  var q = from p in persons where p.Name==name select p;
  return (Person)q;
}

But it gives an error like this
Unable to cast object of type 'WhereListIterator`1[PrsLst.Person]' to type 'PrsLst.Person'.
SO what is the problem and can u help me to fix it.

Upvotes: 2

Views: 594

Answers (4)

Paul Keister
Paul Keister

Reputation: 13097

public Person SelectPerson(string name)
{
  var q = from p in persons where p.Name==name select p;
  return q.FirstOrDefault();
}

Upvotes: 6

Guffa
Guffa

Reputation: 700850

The problem is that the result of the query is a collection of items, even if the collection happens to only contain one item.

Use the Single method to get the single item out of the collection. It also verifies that the collection actually only contains only one item, and throws an exception if it doesn't.

As the collection is known to contain Person items, you don't have to cast the result to Person.

public Person SelectPerson(string name) {
  var q = from p in persons where p.Name==name select p;
  return q.Single();
}

The Single method will also throw an exception if the result is empty. If you rather want to return null in that case, you can use the SingleOrDefault method.

Upvotes: 3

Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

public Person SelectPerson(string name)
{
    Person q = (from p in persons where p.Name==name 
               select p).FirstOrDefault();
    return q;
}

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94653

Try,

public Person SelectPerson(string name)
{
  var q=(from p in persons where p.Name==name select p).FirstOrDefault();;
  return q;
}

Upvotes: 3

Related Questions