C# LINQ Queryable.Single Method in ASP.Net

Updated on 16 Apr 2012,
Published on 11 Feb 2011

The Single Method of System.Linq.Queryable class returns the only single available element from a sequence. It works only if the resulting value is a single element retrieved from the sequence. If the computation evaluates to more than one element then it throws an exception as "Sequence contains more than one element.".  The LINQ Single method has the following two types of overloaded methods which accept one or no parameters to return the desired output:

1.

public static TSource Single<TSource>(this IQueryable<TSource> source);

It takes no parameter and returns a single element from a sequence and throws an exception if the sequence does not have exactly the one element.

2.

public static TSource Single<TSource>(this IQueryable<TSource> source, Func<TSource, bool> predicate);

It accepts one parameter that specifies a predicate to filter the elements of a sequence and returns a single element that satisfies the condition. It also throws an exception if more than one element satisfies the condition.

C# LINQ Single Method Example in ASP.Net

// Example 1:
int[] numbers = { 10 };

int number = numbers.AsQueryable().Single();

Response.Output.Write("{0}<br />", number);

// Example 2:
try
{
    string[] fruits = { "apple", "orange" };

    string fruit = fruits.AsQueryable().Single();

    Response.Output.Write("{0}<br />", fruit);
}
catch (Exception ex)
{
    Response.Output.Write("{0}<br />", ex.Message);
}

// Example 3:
try
{
    string[] fruits = { "apple", "orange" };

    string fruit = fruits.AsQueryable().Single(f => f.StartsWith("a"));

    Response.Output.Write("{0}<br />", fruit);
}
catch (Exception ex)
{
    Response.Output.Write("{0}<br />", ex.Message);
}

// Output:
// 10
// Sequence contains more than one element
// apple

Continue to next tutorial: C# LINQ Queryable.SingleOrDefault Method in ASP.Net to learn how to return default value if the sequence does not contain a single element.

0 Responses to "C# LINQ Queryable.Single Method in ASP.Net"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers