Saturday, October 6, 2012

Conversion of one object collection into another using Linq

In Today's example we will convert an object collection into another object collection using Linq.

As we have seen earlier, using Linq we can eliminate lot of coding effort and can save time also.

For current example i have created an employee collection which contains all the employee details. But some of the employees are authors also.

Now we have to populate an Author collection by filtering the authors from the employee collection.

//Employee class. For the employees who are author also, the //IsAuthor property contains true value
public class Employee
  public string firstName;
  public string lastName;
  public bool IsAuthor;
  public string Country;

  public static ArrayList GetEmployees()
    ArrayList oArrayList = new ArrayList();

    //adding employee details to the array list   
    oArrayList.Add(new Employee { firstName = "Rahul", lastName = "Gupta",Country="India", IsAuthor = true });
    oArrayList.Add(new Employee { firstName = "William", lastName = "Johns", Country = "United States", IsAuthor = true});
    oArrayList.Add(new Employee { firstName = "Stephen", lastName = "Smith", Country = "Australia", IsAuthor = true });
   return (oArrayList);

//Author class 
public class Author
  public string AuthorName;
  public string Country;
  //This display method writes the output to the console window
  public static void DisplayAuthorDetails(Author[] objAuthors)
   //looping through the collection
   foreach (Author c in objAuthors)
     Console.WriteLine("Author Name:  {0}  Country:  {1}", c.AuthorName, c.Country);


//Program class - which contains the Main method of execution
class Program
  static void Main(string[] args)

   ArrayList alEmployees = Employee.GetEmployees();


   //Cast-Converts elements of an IEnumerable to specified type

   //Using Cast to convert Employee object to Author object
   //Where-filters a sequence of values based on predicate
   //Where is used to find all the authors from the employees collection
   Author[] objAuthors = alEmployees.Cast<Employee>()                               
                         .Where(e=> e.IsAuthor==false)
                         .Select(e => new Author { AuthorName = string.Format("{0} {1}",
                                 e.firstName, e.lastName), Country = e.Country})


Happy Coding......

No comments :

Post a Comment