Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#3.5

LINQ (Single, SingleOrDefault)

2.45/5 (3 votes)
16 Dec 2009CPOL 22.9K  
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...
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)
	{
                // The single element of the input sequence.
		Person person1 = (from p in people
					where p.Name = name
					select p).Single();

                // The single element of the input sequence, or default(TSource) if the sequence contains no elements.
		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,

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)