Click here to Skip to main content
11,715,043 members (68,986 online)
Click here to Skip to main content

Tagged as

LINQ (Single, SingleOrDefault)

, 16 Dec 2009 CPOL 13.6K 2
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Programm3r
Technical Lead First Tech Digital Solutions
South Africa South Africa
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.

You may also be interested in...

Comments and Discussions

 
QuestionTitle? Pin
Adam Robinson15-Dec-09 8:48
memberAdam Robinson15-Dec-09 8:48 
AnswerRe: Title? Pin
Programm3r16-Dec-09 18:32
memberProgramm3r16-Dec-09 18:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150901.1 | Last Updated 17 Dec 2009
Article Copyright 2009 by Programm3r
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid