If I have classes of Type A and B:开发者_如何学Python
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?
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..
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.
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.
精彩评论