Tuesday, September 29, 2009

LINQ / Lambda Examples : Convert list of one type to another


///////////////////////////////////////////////////////////////////////////////
//
// Copyright © Schakra Inc. 2009. All rights reserved.
//

///////////////////////////////////////////////////////////////////////////////

using System.Collections.Generic;
using System.Linq;

namespace Schakra.Samples.DotNet.Linq
{
public class LinqSample_01
{
List OutlookContacts { get; set; }

public void ConvertListFromOneTypeToAnother()
{
List winLiveContacts =
OutlookContacts.ConvertAll(
contact => contact.ToWindowsLiveContact());

List outlookContacts =
winLiveContacts.ConvertAll(
contact => new OutlookContact()
{
Name = contact.DisplayName,
Phone = contact.MobilePhone
});

List outlookContacts2 =
(from contact in winLiveContacts
select new OutlookContact()
{
Name = contact.DisplayName,
Phone = contact.MobilePhone
}).ToList();
}
}

public class OutlookContact
{
public string Name { get; set; }

public string Phone { get; set; }

public WindowsLiveContact ToWindowsLiveContact()
{
return
new WindowsLiveContact()
{
DisplayName = this.Name,
MobilePhone = this.Phone
};
}
}

public class WindowsLiveContact
{
public string DisplayName { get; set; }

public string MobilePhone { get; set; }
}
}