28

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?

Jeremy
  • 40,978
  • 63
  • 191
  • 304
  • Your question is unclear... what's the relation between A and B ? – Thomas Levesque Nov 09 '09 at 00:36
  • Essentially they represent the same thing. In my actual case, A is a class generated by Linq to Sql when I created a Linq to Sql class and added a table to it. Because class A has Linq and Linq to Sql dependancies, I do not want to expose it to my applications, so I create class B, that has no dependancies. So I need to populate a list of class B instances from a list of class A instances. – Jeremy Nov 09 '09 at 01:13

3 Answers3

51
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
  • 1,457
  • 12
  • 12
  • Is there a way to filter values out of listA as well so that listB doesn't need to have every item there is in listA? – user20358 Jun 08 '15 at 10:41
  • @user20358 Yes, LINQ has a Where function. Before the ToList() you could call something like this: .Where(w=> w.TotalCount > 5) then call .ToList(); – Troy Harris Jan 27 '21 at 20:25
12
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 it 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.

dckuehn
  • 2,155
  • 3
  • 24
  • 34
eduncan911
  • 16,051
  • 11
  • 61
  • 99
0

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
  • 6,961
  • 2
  • 28
  • 39