I sometimes get asked how to get a single object from a generic list based on a LINQ query. i.e. Performing a LINQ query on a generic collection and then returning only the single instance without looping through the collection. Well this is how I do it:
public class Person
{
public string Name{get;set;}
public string Surname{get;set;}
public int Age{get;set;}
}
public class Example
{
List<Person> people = new List<Person>();
public Example()
{
people.Add(new Person()
{
Name = "Joe",
Surname = "Smith",
Age = 35
});
people.Add(new Person()
{
Name = "John",
Surname = "Doe",
Age = 24
});
people.Add(new Person()
{
Name = "Jane",
Surname = "Doe",
Age = 48
});
}
public Person GetSinglePersonFromList(string name)
{
Person person1 = (from p in people
where p.Name = name
select p).Single();
Person person2 = (from p in people
where p.Name = name
select p).SingleOrDefault();
return person1;
}
}
This is something very small, but think that it might help.
Kind regards,
I escaped from the mental hospital on 25th June and was captured by a zookeeper. Escaped from the zoo on 15th July and killed the zoo guard in the attempt. So now I just eat bananas and hang out on the Code Project.
So you want to surf, and the waves where you live aren't half bad.
And you start to improve ...
And then you hear about this wave in a far-away country, whose name you can't even pronounce. What then?
How far are you willing to go?
What sacrifice are you willing to make? How good do you really want to be?