LINQ - explain about defaultifempty and elementatordefault.

Asked By chitra ganapathy
16-Aug-11 05:19 AM
explain about defaultifempty and elementatordefault with example, in linq to xml
  Vickey F replied to chitra ganapathy
16-Aug-11 05:22 AM

defaultifempty -

Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

example-

public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
	this IEnumerable<TSource> source,
	TSource defaultValue
)

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

This method can be used to produce a left outer join when it is combined with the GroupJoin) method.



  Vickey F replied to chitra ganapathy
16-Aug-11 05:23 AM
elementatordefault-

Returns the element at a specified index in a sequence or a default value if the index is out of range.

The following code example demonstrates how to use ElementAtOrDefault<TSource>. This example uses an index that is outside the bounds of the array.



  string[] names =
                { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
                    "Hedlund, Magnus", "Ito, Shu" };

            int index = 20;

            string name = names.ElementAtOrDefault(index);

            Console.WriteLine(
                "The name chosen at index {0} is '{1}'.",
                index,
                String.IsNullOrEmpty(name) ? "<no name at this index>" : name);

            /*
             This code produces the following output:

             The name chosen at index 20 is '<no name at this index>'.
            */

Hope this will help you.
  Radhika roy replied to chitra ganapathy
16-Aug-11 05:26 AM

 

ElementAtOrDefault returns the element at a given index, or the defaultvalue of the list type. For value types (ints and bools for example), the default value is the initial value of the type, which is usually 0. For reference types (objects), the default value is usually null, although this can be overriden. 

LINQ ElementAt and LINQ ElementAtOrDefault Example:


// Create a new generic list of ints
List<int> l = new List<int>();

l.Add(1); // Add 1 to the list
l.Add(5); // Add 5 to the list
l.Add(3); // Add 3 to the list

// Returns 1 as 1 exists at index 0
int value = l.ElementAt(0);

// Returns 3 as 3 exists at index 2
value = l.ElementAt(2);

// Returns the default value of int which is 0 
// since no element in the list exists at index 3
value = l.ElementAtOrDefault(3);

// Throws System.ArguementOutOfRangeException 

// since no element in the list exists at index 3


value = l.ElementAt(3);
 

for more help follow this link-

http://blog.linqexchange.com/index.php/using-linq-elementat-and-linq-elementatordefault/

Hope this will help you.

  Radhika roy replied to chitra ganapathy
16-Aug-11 05:28 AM


DefaultIfEmpty-

Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.


Namespace:
  System.Linq
Assembly:  System.Core (in System.Core.dll)


Example-


Suppose you have a tblRoom and tblUserInfo. Now, you need to select all the rooms regardless of whether the room has user information or not. This calls for a LEFT JOIN which will select everything from the LEFT side (the room side) regardless of the join on the right side. Here is the example. 

 var list = from r in dc.tblRooms
               join ui in dc.tblUserInfos
               on r.UserName equals ui.UserName into userrooms
               where r.CourseID == 1848

               from ur in userrooms.DefaultIfEmpty()

               select new
               {
                 FirstName = (ur.FirstName == null) ? "N/A" : ur.FirstName,
                 LastName = (ur.LastName == null) ? "N/A" : ur.LastName,
                 RoomName = r.Name
                 
               };

The anonymous type replaces the "null" FirstName and LastName with "N/A" (not available). 

Hope this will help you.

  Riley K replied to chitra ganapathy
16-Aug-11 05:44 AM

The “DefaultIfEmptyoperator returns a single element sequence if the output sequence is empty. The single element will be “default(T) or the specified value. If the source sequence is not empty, it returns the source sequence itself.

Example 

IEnumerable<Employee> emps = Employee.GetEmployees();
 
var newEmps
  = emps.Where(e => e.CityID == 3).DefaultIfEmpty();
foreach (var e in newEmps)
{
  if (e != null)
  {
    Console.WriteLine("{0}", e.Name);
  }
  else
  {
    Console.WriteLine("No employee lives in City whose ID is 3");
  }
}

The “ElementAtOrDefaultoperator returns the element at a specified index in a sequence. If the index is out of range, it returns a default value of the type.

 Example 

IEnumerable<Employee> emps = Employee.GetEmployees();
 
Employee emp = emps.Where(e => e.Name.Contains("Smith")).ElementAtOrDefault(1);
Console.WriteLine("Matching Employee: {0}", emp.Name);
 // Mark Smith
 
Employee emp1 =   emps.Where(e => e.Name.Contains("Smith")).ElementAtOrDefault(2); // out of index
 
if (emp1 == null)
 
{
  Console.WriteLine("Out of Index");
}


Regards
  Anoop S replied to chitra ganapathy
16-Aug-11 05:51 AM
The ElementAtOrDefault method of System.Linq.Queryable class enables to get the element at specified index or it returns a default value if the specified index is out of range. The LINQ ElementAtOrDefault method accepts only one parameter as integer type that returns a particular element from the sequence. If the specified index does not exist then this method returns default value based on the data type of element of the sequence or returns null for Nullable types. The Linq ElementAtOrDefault method does not have any overloaded function. It has a following single form:

public static TSource ElementAtOrDefault<TSource>(this IQueryable<TSource> source, int index);

It accepts an integer type value to specify the index and returns the element from a sequence at that index.
C# LINQ ElementAtOrDefault Method Example in ASP.Net

List<Employee> Employees = new List<Employee>()
{
    new Employee(1, "Terry", "Adams", 30, 5),
    new Employee(2, "Hugo", "Garcia", 27, 3),
    new Employee(3, "Fadi", "Fakhouri", 32, 5),
    new Employee(4, "Debra", "Garcia", 30, 4),
    new Employee(5, "Lance", "Tucker", 35, 7),
    new Employee(6, "Hanying", "Feng", 35, 5),
    new Employee(7, "Michael", "Tucker", 28, 5),
    new Employee(8, "Eugene", "Zabokritski", 40, 10),
    new Employee(9, "Sven", "Mortensen", 37, 8),
    new Employee(10, "Svetlana", "Omelchenko", 36, 7)
};

Employee employee = Employees.AsQueryable().ElementAtOrDefault(4);

Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);

employee = Employees.AsQueryable().ElementAtOrDefault(15);

if (employee != null)
    Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);
else
    Response.Output.Write("No item found.<br />");

// Output:
// Lance Tucker
// No item found.

C# Employee Class:

public class Employee
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public int Experience { get; set; }

    public Employee(int Id, string firstName, string lastName, int age, int experience)
    {
      this.ID = Id;
      this.FirstName = firstName;
      this.LastName = lastName;
      this.Age = age;
      this.Experience = experience;
    }
}

In the above C# sample we have tried the Linq ElementAtOrDefault method two times. First we have specified the index within the range of List collection. In the second call to ElementAtOrDefault method we have specified the index out of range of List collection that will return a null object for Employee class object.
  Anoop S replied to chitra ganapathy
16-Aug-11 05:53 AM
defaultifempty-> This is a very handy way to test if an element exists using LINQ
Often you want to run something only if an element exists. There is always the try/catch method, but that doesn't seem very elegant to me, and this gave me an excuse to figure some more out about LINQ, which I am finding I like more and more.

This is actually very simple once you understand how DefaultIfEmpty() works. It may seem a bit obvious, but it returns a default value if something is not there. The easiest way to do this is to give it something explicitly so you know what it is returning for the default; I just use a dummy instance. For this example, I am using LINQ with XML and XElements

//make your dummy element
XElement dummy = new XElement("dummy");
//assign it an easy to recognize null value
dummy.Value = "Does Not Exist";
//now run a query with it
foreach (XElement p in xmlFromFile.Elements("anElement").Descendants("someElement").DefaultIfEmpty(dummy))
{
  if(process.Value.Equals("Does Not Exist")
    //it does not exist
}
It's just that easy. Works the exact same with SQL or any other data source as well.
Create New Account
help
LINQ ElementAtOrDefault Query Operator Returns the element at a specified index in a sequence or a default Adams, Terry" , "Andersen, Henriette Thaulow" , "Hedlund, Magnus" , "Ito, Shu" }; int index = 20; string name = names. ElementAtOrDefault (index); Console . WriteLine ( "The name chosen at index {0} is '{1}'." , index, String . IsNullOrEmpty (name) ? "<no name at this index> " : name); / * This code produces the following output: The name chosen at index 20 is '<no name at this index> ' . * / LINQ ElementAtOrDefault Query Operator ( 110 Views ) View Peter Bromberg's FAQs Create New Account keywords: ElementAtOrDefault, IsNullOrEmpty, string, int description: Returns the element at a specified index in a sequence or a
LINQ ElementAtOrDefault Query Operator Returns the element at a specified index in a sequence or a default Adams, Terry" , "Andersen, Henriette Thaulow" , "Hedlund, Magnus" , "Ito, Shu" }; int index = 20; string name = names. ElementAtOrDefault (index); Console . WriteLine ( "The name chosen at index {0} is '{1}'." , index, String . IsNullOrEmpty (name) ? "<no name at this index> " : name); / * This code produces the following output: The name chosen at index 20 is '<no name at this index> ' . * / LINQ ElementAtOrDefault Query Operator ( 54 Views ) View Peter Bromberg's FAQs Create New Account keywords: ElementAtOrDefault, IsNullOrEmpty, string, int description: Returns the element at a specified index in a sequence or a
LINQ DefaultIfEmpty Generation Operator The DefaultIfEmpty operator supplies a default element for an empty sequence. One use of this operator is pic = (from p3 in u.tbl_pics where p3.tbl_user. ID = = u. ID select p3.pic_path). DefaultIfEmpty ( "defaultpic.jpg" ). First ()}). ToList (); LINQ DefaultIfEmpty Generation Operator ( 193 Views ) View Peter Bromberg's FAQs Create New Account keywords: ToList, ID, DefaultIfEmpty, var description: The DefaultIfEmpty operator supplies a default element for an empty sequence. One use of this operator is