views:

157

answers:

3

If I have classes of Type A and B:

public class A
{
    public int TotalCount;
    public string Title;
}

public class B
{
    public int Count;
    public string Title;
}

I have a list of instances A instances, what is the most efficient way to create and populate a List of type B using Linq?

+3  A: 
var list = 
  from a in TableA
  select new B {
    Count = a.TotalCount
    , Title = a.Title
  };

You new up an instance of B in your select clause, and assign the properties using the inline property assignment feature in C# 3.0.

The advantages of mapping it inline comes from deferred execution of your Linq statement. Linq will map the modified statement, and execute it from your IQueryable. For example:

public class ClassA 
{
  public int TotalCount;    
  public string Title;
}

public class ClassB
{
  public int Count;
  public string Title;
}

public IQueryable<ClassB> FetchAllOfClassB()
{
  var list = 
    from a in TableOfClassA
    select new ClassB {
      Count = a.TotalCount
      , Title = a.Title
    };

  return list.AsQueryable();
}

Technically, the AsQueryable is a bit redundant. Sometimes I use to to make it a point, others say it is absolutely required. None the less, the list object itself is IQueryable of ClassB.

Then you can call FetchAllOfClassB() further up the chain, and use IQuerable. It's pretty slick, and efficient.

eduncan911
Just about to write something like this, but you've got it covered! +1
RCIX
I love linq. +1.
Daniel M
THanks guys. Upped your comments as well. :)
eduncan911
A: 

Hmm, off the top of my head (so there will probably be errors!):

List< B > = from a in listOfA select new B(a.count, a.title);

might do the trick.

Jeff Paquette
+1  A: 
List<B> listB = listA.Select(a => new B()
   {
        Count = a.TotalCount,
        Title = a.Title
   }).ToList();

Does the same as eduncan's solution with different syntax. Take your pick..

Daniel M